需要注意两个地方:
1:IE下会乱码,所以需要用userAgent那个部分来处理
2:进入方法以后不会下载,没有反应,我这边的情况是因为我用了AJAX提交,所以要解决这个问题
1:设置AJAX参数
2:换一种请求方法,不用AJAX
public ActionForward creatCollectFileReport(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String filePath = getMyParamPlus(request, "filePath", "");
String userAgent = request.getHeader("User-Agent");
String fileName = "";
int start = filePath.lastIndexOf("/");
if (start != -1) {
fileName = filePath.substring(start + 1);
}
StringBuffer localStringBuffer = new StringBuffer(50);
FileInputStream localFileInputStream = null;
BufferedOutputStream localBufferedOutputStream = null;
File localFile1 = new File(filePath);
if ((localFile1 != null) && (localFile1.exists())
&& (localFile1.isFile())) {
long l = localFile1.length();
try {
localFileInputStream = new FileInputStream(localFile1);
response.reset();
response.setContentType("application/octet-stream");
response.setContentLength((int) l);
// 针对IE或者以IE为内核的浏览器:
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} else {
// 非IE浏览器的处理:
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-Disposition","attachment;filename="+ new String(fileName.getBytes("utf-8"),"ISO-8859-1"));
localBufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
try {
byte[] arrayOfByte1 = new byte[2048];
int i;
while ((i = localFileInputStream.read(arrayOfByte1)) > 0) {
localBufferedOutputStream.write(arrayOfByte1, 0, i);
}
localBufferedOutputStream.flush();
} catch (Exception localException2) {
}
localBufferedOutputStream.close();
localFileInputStream.close();
} catch (Exception localException3) {
}
}
try {
if (localBufferedOutputStream != null) {
localBufferedOutputStream.flush();
localBufferedOutputStream.close();
}
if (localFileInputStream != null) {
localFileInputStream.close();
}
} catch (Exception localException1) {
}
return null;
}