java文件下載以及中文亂碼解決


  在客戶端下載文件時替換下載文件的名稱,但是當名稱是中文時瀏覽器會出現亂碼,解決代碼如下:

    public org.springframework.http.ResponseEntity<InputStreamResource> handleExcel(HttpServletRequest request) throws Exception {
        String fileName = "模板下載.xsls";
            //解決瀏覽器下載漢字亂碼的兼容問題
            String userAgent = request.getHeader("User-Agent");
            byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8");
            // 各瀏覽器基本都支持ISO編碼
            String name = new String(bytes, "ISO-8859-1");
             //網絡資源文件
             //可以替換為網絡資源文件
             //本地文件
            PathResource file = new     PathResource(FileUtil.getNewFileName(fileName));
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", "attachment;fileName=" + name);
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            org.springframework.http.ResponseEntity<InputStreamResource> entity = org.springframework.http.ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.contentLength())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(file.getInputStream()));
            return entity;
}                    

  


免責聲明!

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



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