如何强制RestController响应csv文件

时间:2018-02-15 23:04:55

标签: java spring csv spring-boot swagger

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

这是我的Api界面:

@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)。

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

您需要将返回类型更改为 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);
    }

答案 1 :(得分:-1)

尝试将生产输出MIME类型更改为text/csv