java IE11瀏覽器檔案下載的檔名亂碼
阿新 • • 發佈:2019-01-06
專案中有用到檔案下載功能,之前在處理下載時對IE瀏覽器下檔案下載名進行過處理,測試也沒有問題,
但是功能上線後,業務反饋IE11檔案下載檔名依然亂碼。列印User-Agent字串如下:
IE11 User-Agent字串:Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
IE6~IE10版本的User-Agent字串:Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.0; Trident/6.0)
但是功能上線後,業務反饋IE11檔案下載檔名依然亂碼。列印User-Agent字串如下:
IE11 User-Agent字串:Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
IE6~IE10版本的User-Agent字串:Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.0; Trident/6.0)
IE瀏覽器在IE11,更改了User-Agent字串格式內容,所以針對IE11,做一下判斷即可:
//下載檔案,並處理檔名亂碼 public void downloadFile(HttpServletRequest request,HttpServletResponse response){ String path = request.getSession().getServletContext().getRealPath("/upload/文件1.doc"); // path是根據日誌路徑和檔名拼接出來的 File file = new File(path); //獲取日誌檔名稱 String filename = file.getName(); try { //判斷是否是IE11 Boolean flag= request.getHeader("User-Agent").indexOf("like Gecko")>0; if (request.getHeader("User-Agent").toLowerCase().indexOf("msie") >0||flag){ filename = URLEncoder.encode(filename, "UTF-8");//IE瀏覽器 }else { //先去掉檔名稱中的空格,然後轉換編碼格式為utf-8,保證不出現亂碼, //這個檔名稱用於瀏覽器的下載框中自動顯示的檔名 filename = new String(filename.replaceAll(" ", "").getBytes("UTF-8"), "ISO8859-1"); //firefox瀏覽器 //firefox瀏覽器User-Agent字串: //Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0 } InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer; buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); response.addHeader("Content-Disposition", "attachment;filename=" +filename); response.addHeader("Content-Length", "" + file.length()); OutputStream os = response.getOutputStream(); response.setContentType("application/octet-stream"); os.write(buffer);// 輸出檔案 os.flush(); os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }