Monicase 2017-11-05 14:06 采纳率: 25%
浏览 21640

springboot ResponseEntity 实现文件下载(文件损坏,以及乱码)

AttachedFile attachedFile = attachedFileService.selectById(fileId);
String filePath = pathHead + attachedFile.getFilePath();
String fileName = attachedFile.getFileName() + "." + attachedFile.getExtension();
FileSystemResource file = new FileSystemResource(filePath);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(file.getInputStream()));
//HttpHeaders headers = new HttpHeaders();
////下载显示的文件名,解决中文名称乱码问题
//String downloadFileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
////通知浏览器以attachment
//headers.setContentDispositionFormData("attachment", downloadFileName);
////application/octet-stream : 二进制流数据(最常见的文件下载)。
//headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//return new ResponseEntity<>(FileUtils.readFileToByteArray(file),
// headers, HttpStatus.CREATED);

    我是按照网上正常给的教程写的,但是就是文件损坏,(好像是数据流就不对)

    ![图片说明](http://i![图片说明](https://img-ask.csdn.net/upload/201711/05/1509890721_393189.png)mg.ask.csdn.net/upload/201711/05/1509890701_819933.png)
  • 写回答

2条回答 默认 最新

  • zkh11123 2018-04-20 03:07
    关注

    我也被这个问题困扰了蛮久。归根到底还是不了解springboot的配置。
    mvc的配置如何转换成springboot的配置就是解决这个问题的关键

    1楼回答的是在MVC配置文件里面解决。

    springboot的解决方案是增加如下一个类 去配置 MessageConverters。
    加上注解@Configuration 就会被springboot加载配置。成功解决如上问题。

    @Configuration
    public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        converters.add(new ByteArrayHttpMessageConverter());
    }
    

    }

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog