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

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,是为了兼容更多浏览器。

转载于:https://www.cnblogs.com/tanzx/p/7744959.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值