今天遇到一个问题,文件下载,如果有空格,浏览器下载的时候会丢失文件名 - -。
之前下载的代码:
@RequestMapping("download")
public void downloadFile(long fileId, HttpServletResponse response){
AttachedFile attachedFile = attachedFileManager.getFile(fileId);
String filePath = UPLOAD_PATH + File.separatorChar + attachedFile.getWebAccessPath();
String fileName = null;
try {
fileName = new String((attachedFile.getFileName()).getBytes("UTF-8"), "iso8859-1");
response.reset();
response.setHeader("Content-Disposition", "attachment;filename="+ fileName);// 指定下载的文件名
response.setContentType("application/octet-stream; charset=UTF-8");
//response.setContentType("application/vnd.ms-excel");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
InputStream is = new FileInputStream(filePath);
OutputStream os = response.getOutputStream();
byte[] b = new byte[1024];
int length;
while((length = is.read(b)) > 0) {
os.write(b, 0, length);
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Google之下,什么解决方案的都有。比如把文件名utf8加密(URLEncode),然后把“+”替换成%20,测试之后没用!
然后转成英文搜索,在stackoverflow发现一个方案。
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
这样确实很好用 - -. 记录下...以免别人以后找不到答案...
注意:fileName最后被双引号("")包起来了...另外,文件名乱码的问题,看代码就好了,fileName被转码了一次。。。