背景:项目中大量使用a标签href属性直接写文件资源路径,在火狐浏览器上可以直接使用,但是在ie8下则在浏览器直接打开,显示为乱码,为尽量减少修改,写以下代码。
js代码
java代码
@Action
public void downloadTemplate() {
HttpServletResponse response = ActionContext.getActionContext().getHttpServletResponse();
HttpServletRequest resquest = ActionContext.getActionContext().getHttpServletRequest();
String filePath = resquest.getParameter("filePath");
String resourcePath = System.getProperty("resourceFiles.location");
filePath = filePath.replace("/ResourceFiles", resourcePath);
try {
// path是指欲下载的文件的路径。
File file = new File(filePath);
// 取得文件名。
String fileName = file.getName();
// 特殊处理火狐浏览器中文乱码问题。
String agent = resquest.getHeader("USER-AGENT");
if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
fileName = "=?UTF-8?B?" + (new String(Base64.getEncoder().encode(fileName.getBytes("UTF-8")))) + "?=";
} else {
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
}
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.setContentType("text/html;charset=UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}