·1. 文件下载的时候需要设置响应头
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" +fileName);
2.当文件名出现中文的时候,还需要解决文件名乱码的问题
中文名称下载文件乱码,主要要做Firefox,IE和chrome这三个浏览器的适配。
下面是常用浏览器的user-agent
IE11
Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko
IE6
Mozilla/4.0 (Windows; MSIE 6.0; Windows NT 5.2)
edge
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134
FireFox window
Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0
Firefox mac
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0
Google window
Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36
Google mac
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36
注: 以上User-Agent有些是用魔变插件模拟出来的。
- IE浏览器,它们的User-AGENT可能有这三种可能,”MSIE,“Trident”,“Edge”。IE浏览器,使用utf-8对文件名编码就可以了, URLEncoder.encode(fileName,"UTF8");
- Firefox 可以使用“Firefox”区分,new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
- chrome 比较随和没有比较突出的关键字,所以以上两种方式都可以。
java public void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) { String userAgent = request.getHeader("USER-AGENT"); try { String finalFileName = null; if(StringUtils.contains(userAgent, "MSIE")||StringUtils.contains(userAgent, "Trident") || StringUtils.contains(userAgent,"Edge")){//IE 浏览器 finalFileName = URLEncoder.encode(fileName,"UTF8"); }else{ finalFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); } response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");//\" 解决Firefox下载英文+中文组合的文件名的问题 } catch (UnsupportedEncodingException e) { } }