Spring MVC文件下載的文件名編碼問題
阿新 • • 發佈:2017-10-27
tar exception color res eno ont ted exceptio throw
Spring MVC做文件下載功能時,遇到了文件名編碼問題。經過百度,參考了以下兩篇文章,解決了編碼問題。
http://www.iefans.net/xiazai-wenjian-http-bianma-content-disposition/
https://yq.aliyun.com/articles/38945
最終代碼如下:
public ResponseEntity<InputStreamResource> downloadFile(Path filePath) throws FileNotFoundException { File file= filePath.toFile(); String mimeType = URLConnection.guessContentTypeFromName(file.getName()); if (mimeType == null) { mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE; } HttpHeaders respHeaders = new HttpHeaders(); respHeaders.set(HttpHeaders.CONTENT_TYPE, mimeType); respHeaders.setContentLength(file.length()); String encodedFileName= file.getName(); try { encodedFileName = URLEncoder.encode(encodedFileName, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.error("文件名編碼錯誤!", e); } respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"" + "; filename*=UTF-8‘‘" +encodedFileName); InputStreamResource isr = new InputStreamResource(new FileInputStream(file)); return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK); }
先對原始文件名按UTF-8編碼,再設置Content-Disposition。Content-Disposition中設置了兩次filename,是為了兼容更多瀏覽器。
Spring MVC文件下載的文件名編碼問題