首页 > 其他 > 详细

随手记一个问题

时间:2020-07-29 10:54:35      阅读:90      评论:0      收藏:0      [点我收藏+]

文件下载时,Response获取的writer写字节流下载文件没有文件名导致客户端收到的文件是以文件后缀作为文件名,且没有后缀的文件

技术分享图片

 

如下载下来的会是上述类型的文件。

F12点开控制台查看响应体发现文件名乱码,推测是因为浏览器没能识别文件名。解决办法:

在对客户端写文件之前,对文件名进行URL编码:

 

response.addHeader("Content-Disposition","attachment;fileName="+fileName);

  其中fileName包含后缀。

        String fileName=StringUtils.EMPTY;
        response.setContentType("application/x-download");
        try {
            fileName=URLEncoder.encode(dto.getFileName(),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("utf8编码失败");
            fileName=dto.getFileName();
        }
        response.addHeader("Content-Disposition","attachment;fileName="+fileName);
        response.setHeader("success", "true");
        OutputStream outputStream=null;
        try {
            outputStream =  response.getOutputStream();
            outputStream.write(content);
        }catch (IOException e){
            log.error("写文件流失败,失败原因【{}】",e.getMessage());
        }finally {
        }

  

随手记一个问题

原文:https://www.cnblogs.com/notably/p/13395064.html

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