我正在开发一个 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/