springboot下载文件抛异常

一个下载文件的方法,每次文件都能成功下载,但控制台总会报错:

java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class java.lang.Boolean] with preset Content-Type 'application/octet-stream;charset=UTF-8'

在这里插入图片描述

参考文章

Cannot call sendError() after the response has been committed

【SSH问题】java.lang.IllegalStateException: Cannot call sendError() after the response has been committe

  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Spring Boot提供了基于`Resource`的方式进行文件下载,代码如下: ```java @GetMapping("/download/{fileName}") public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) { Resource resource = new FileSystemResource("/path/to/files/" + fileName); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\""); return ResponseEntity.ok() .headers(headers) .contentLength(resource.contentLength()) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(resource); } ``` 其中,`@GetMapping("/download/{fileName}")`表示接收以`/download/`开头后跟文件名的请求,`${fileName}`会被映射到方法参数中的`fileName`中。 `FileSystemResource`是Spring提供的一个以文件系统路径为参数的`Resource`实现,可以用来加载本地文件资源。如果需要从其他位置加载文件资源,可以使用其他实现方式,如`UrlResource`或者`ClassPathResource`。 `HttpHeaders`用于设置response的header信息,此处使用了`CONTENT_DISPOSITION`头,表示文件下载时需要显示“保存文件”的对话框,并将文件名设置为`fileName`。 最后,使用`ResponseEntity`打包文件资源,设置Content-Type为`APPLICATION_OCTET_STREAM`,即二进制流类型,之后返回`Resource`即可。 需要注意的是,如果需要下载的资源不存在,会出404错误。同时,如果文件下载时出现异常,建议使用异常拦截器统一处理。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值