java文件下载以及中文乱码解决
生活随笔
收集整理的這篇文章主要介紹了
java文件下载以及中文乱码解决
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在客戶端下載文件時替換下載文件的名稱,但是當(dāng)名稱是中文時瀏覽器會出現(xiàn)亂碼,解決代碼如下:
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");//網(wǎng)絡(luò)資源文件//可以替換為網(wǎng)絡(luò)資源文件//本地文件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; }
轉(zhuǎn)載于:https://www.cnblogs.com/wiseroll/p/10265665.html
總結(jié)
以上是生活随笔為你收集整理的java文件下载以及中文乱码解决的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python描述器
- 下一篇: python基础学习笔记——方法返回值