java - 如何强制RestController响应csv文件

标签 java spring csv spring-boot swagger

我正在开发一个 Rest API,将负责返回 csv 文件作为响应。

这是我的 Api 接口(interface):

@Api(value = Constantes.REPORTS)
public interface ExtractFileApi {
  @RequestMapping(value = Constantes.REPORTS_URL, produces = "application/csv", method = RequestMethod.GET)
  public ResponseEntity<InputStreamResource> getExtractFile() throws IOException;
}

这是我的界面实现:

@RestController
public class ExtractFileApiController implements ExtractFileApi {
    @Override
    public ResponseEntity<InputStreamResource> getExtractFile() throws IOException {
     ClassPathResource pdfFile = new ClassPathResource("pdf-sample.csv");
     HttpHeaders headers = new HttpHeaders();
     headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
     headers.add("Pragma", "no-cache");
     headers.add("Expires", "0");

     return ResponseEntity.ok().headers(headers).contentLength(pdfFile.contentLength())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(new InputStreamResource(pdfFile.getInputStream()));
}

目前,我的 API 返回下载文件的链接,但我不知道如何强制响应完全是 CSV 文件 (file.csv)。

谁能帮帮我吗?

最佳答案

您需要将返回类型更改为void,然后在末尾使用以下代码

Path path = Paths.get(pdfFile.getPath()); 
response.setHeader("content-disposition", "attachment; filename="
            + path.getFileName().toString().replace(" ", "_"));
    try {
        response.setContentType(Files.probeContentType(path));
        response.setContentLength((int) Files.size(path));
        // Copy bytes from source to destination, closes both streams.
        FileCopyUtils.copy(Files.newInputStream(path),
                response.getOutputStream());
    } catch (IOException e) {
        LOGGER.error("fetching file failed", e);
        response.setStatus(500);
    }

关于java - 如何强制RestController响应csv文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48817713/

相关文章:

java - switch 语句中一组字符串值的输入验证

java - 应用程序服务器/平台无关的 Bayeux 实现

python - 从 JSON 到 CSV 的字典

python - 在 Python 中创建并附加带有标题的 CSV 文件一次

java - 获取ManyToMany映射表的id

Powershell - 将日志文件转换为 CSV

java - 使用 ffmpeg 将 flv 转换为 mp4

java - 为什么 Java 编译器不允许我返回泛型类型?

spring - 我们可以从复合键属性中构建 Spring Data JPA 规范吗

java - MongoDB 嵌入式对象没有 ID(空值)