为什么要用sevlet进行文件下载,而不是直接把url放在直接anchor里面:
<a href="setup.exe">download</a>
使用上面的方法遇到两个问题:
1.如果用户已经下载过文件,firefox会cache文件,用户再次进行下载时,会从cache里面下载,这样用户可能永远无法拿到最新的安装文件了,除非他清除浏览器的cache
2.尝试在url里面加入时间戳:<a href="setup.exe?time=<%=System.currentTimeMillis()">download</a>
FireFox 中问题解决,但是出现了一个新的问题:ie点击下载后,居然是未知类型的setup文件。
只好用个servlet下载了,对应servlet加入时间戳:
<ahref='downloadSetupApp.do?time=<%=System.currentTimeMillis()%>
Java文件如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class DownloadSetupAppAction extends BaseActionSupport {
public static final Log sysLog = LogFactory
.getLog(DownloadMiniAppAction.class);
/**
* **********************************************************************
* This API is used to download the Setup.exe application. Why need to
* download the file using the servlet rather than directly add
* a link to the page:
* 1.In FireFox, the file is always cached, thus the latest version
* always download from the cache rather than from the site. So the user
* can not get the latest version when he has downloaded the applicaton
* before.
*
* 2.When add a time stamp to prevent cache by the browser, the IE can not
* know the type of the application. So user can not directly install it
* directly
*
*/
public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
HttpServletRequest request, HttpServletResponse response) {
String downloadPath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/exe/setup.exe";
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0L);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/force-download");
OutputStream out = null;
InputStream fileInputStream = null;
try {
String disHeader = "Attachment;Filename=\"setup.exe\"";
response.setHeader("Content-Disposition", disHeader);
out = response.getOutputStream();
// transfer the file byte-by-byte to the response object
URL url = new URL(downloadPath);
URLConnection con = url.openConnection(); // *
con.connect();
fileInputStream = con.getInputStream();
int i;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
} catch (IOException e) {
log.error(e, e);
} catch(Exception e){
log.error(e,e);
}
finally {
try {
if(fileInputStream!=null){
fileInputStream.close();
}
if(out!=null){
out.close();
}
} catch (IOException e) {
log.error(e,e);
}
}
return null;
}
}