下载文件报错: Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class org.springframework.core.io.FileSystemResource] with preset Content-Type 'application/pdf']

已经设置了 .contentType(MediaType.APPLICATION_PDF)

报错:

Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class org.springframework.core.io.FileSystemResource] with preset Content-Type 'application/pdf']

代码:

    public ResponseEntity<FileSystemResource> download(String shippingLabelFile) throws IOException {

        Path path = Paths.get(filePath, shippingLabelFile).normalize();
        log.info("下载文件名称:{}",shippingLabelFile);
        if (Files.notExists(path) || Files.isDirectory(path)) {
            ResponseEntity.notFound();
        }
        try {
            File file = new File(filePath + "/" + shippingLabelFile);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", "attachment; filename=" + shippingLabelFile);
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            headers.add("Last-Modified", new Date().toString());
            headers.add("ETag", String.valueOf(System.currentTimeMillis()));
            return   ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .contentType(MediaType.APPLICATION_PDF)
                    .body(new FileSystemResource(file));

        } catch (Exception e) {
            e.printStackTrace();
            log.info("dfsId:{}下载文件失败,cause:{}",shippingLabelFile,e);
        }
         return null;
    }

public ResponseEntity<FileSystemResource> 修改为 public ResponseEntity<Resource> 试试看。

不行,还是报这个错

把ContentType换一下

.contentType(MediaType.APPLICATION_OCTET_STREAM)
 No converter for [class org.springframework.core.io.FileSystemResource] with preset Content-Type 'application/octet-stream']

报这个

  return   ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(new FileSystemResource(file));

这个最后的body 还有没有别的封装方式

FileSystemResource换成 InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

看了下源码。Resource 实现只能用 InputStreamResource 或者是 ByteArrayResource

1 个赞