随手记一个问题

文件下载时,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 {
        }

  

猜你喜欢

转载自www.cnblogs.com/notably/p/13395064.html