Springboot ResponseEntity IE無法正常下載文件


項目在google瀏覽器下都很nice了,但當測試到IE的時候開始出現各種問題。

項目是前端js通過URL傳參fileName到后台解析返回ResponseEntity

前端代碼如下:

window.location.href="downPlan.do?fileName=fileName;

后台代碼:

@RequestMapping({"/downPlan.do"})
    //@ResponseBody
    public ResponseEntity<byte[]> downPlan(HttpServletRequest request, @RequestParam("fileName") String fileName) throws Exception {
        String path = "C:/check/plan/";
        String fName =fileName+".xlsx";
        File file = new File(path + File.separator + fName);
        if(!file.exists()){
            fName =fileName+".xls";
             file = new File(path + File.separator + fName);
        }
        HttpHeaders headers = new HttpHeaders();
        String downloadFielName = new String(fName.getBytes("UTF-8"), "iso-8859-1");
        headers.setContentDispositionFormData("attachment",downloadFielName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}

 

1、測試IE9下,出現錯誤:The valid characters are defined in RFC 7230 and RFC 3986,百度原因好像是URL中包含了超出RFC 7230和RFC 3968所定義的字符

解決方法:可以換tomcat的版本,過於麻煩

或者修改tomcat配置文件

我選了個最簡單的編碼 - 反編碼

前端修改成

window.location.href="downPlan.do?fileName="+encodeURI(encodeURI(fileName));

后台反編碼即可

fileName = URLDecoder.decode(fileName,"UTF-8");

 

2、IE下載文件異常,文件名是URL的地址

異常如下圖:

      

廢話不多說:HttpStatus.CREATED改為HttpStatus.OK即可以,因為IE不支持201狀態

return new ResponseEntity(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);

3、下載文件會出現中文亂碼

文件可以正常下載,但是出現亂碼就很煩了。

 google可以正常顯示,IE則會出現亂碼,header中只支持ASCII所以我們傳輸的文件名必須是ASCII,

 String downloadFielName = new String(fName.getBytes("UTF-8"), "iso-8859-1");

google可以自動識別編碼方式,會對其進行反解碼,而IE則只會用GBK的方法,所以IE下載文件名還是亂碼,改成以下:

    String downloadFielName = new String(fName.getBytes("GBK"), "iso-8859-1");

把UTF-8改成GBK即可

詳情參考大神的博客:https://yq.aliyun.com/articles/38945


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM