首页 > 编程语言 > 详细

Spring MVC文件下载的文件名编码问题

时间:2017-10-27 20:29:40      阅读:269      评论:0      收藏:0      [点我收藏+]

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文件下载的文件名编码问题

原文:http://www.cnblogs.com/tanzx/p/7744959.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!