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

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 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器