Java 解决IE浏览器下载文件,文件名出现乱码问题

2018-03-02 by 紫薇帝星的故事

/** * 区分ie 和其他浏览器的下载文件乱码问题 * @param request * @param fileName * @return */ public String getFileName(HttpServletRequest req,String fileName){ String userAgent = req.getHeader("user-agent"); userAgent = userAgent ==null?"":userAgent.toLowerCase(); String name = fileName; try {
       //针对IE或者以IE为内核的浏览器: if(userAgent.contains("msie") ||userAgent.contains("trident")){ name = URLEncoder.encode(name, "UTF-8"); }else{ name = new String(name.getBytes(), "iso-8859-1"); } } catch (Exception e) { throw new SysException(ERRORConstants.COMMON_SYSTEM_ERROR, e); } return name; }

  网上很多例子是用 msie  和like Gecko  来做区分,说ie11去除了msie;

 亲自测试 谷歌浏览器也带like Gecko,ie11的 msie没有移除,并且带有trident标记

结论是 不用用like Gecko来做区分,最后

public void exportExcel(HttpServletRequest req,HttpServletResponse response) { try{ response.setContentType("application/octet-stream"); String excelName = "文件名"; response.addHeader("Content-Disposition", "attachment;filename="+getFileName(req,excelName)+".xls"); OutputStream out = response.getOutputStream(); testService.export(out); }catch(Exception e){// } }
最新更新:

第七城市

栏目导航(关闭)