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

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 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥50 Oracle Kubernetes服务器集群主节点无法访问,工作节点可以访问
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。
  • ¥15 stm32的can接口不能收发数据
  • ¥15 目标检测算法移植到arm开发板
  • ¥15 利用JD51设计温度报警系统