2 回答
TA贡献1982条经验 获得超2个赞
您可以在响应的输出流中写入数据。
@RequestMapping(value = "/getcsv", method = RequestMethod.GET)
public void getCSV(HttpServletResponse response){
String csv = "a,b";
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "fileName.csv");
response.setHeader("Access-Control-Expose-Headers","Authorization, Content-Disposition");
try (PrintWriter pw = new PrintWriter(response.getOutputStream())) {
pw.write(csv);
}
}
TA贡献1818条经验 获得超8个赞
您可以尝试以下代码。
@PostMapping(value = "/getcsv", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<?> downloadFile(@RequestParam("fileName") String fileName) {
String dirPath = "E:/some-directory-path/";
byte[] fileBytes = null;
try {
fileBytes = Files.readAllBytes(Paths.get(dirPath + fileName));
} catch (IOException e) {
e.printStackTrace();
}
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
.body(fileBytes);
}
您必须设置为 Application Octet Stream 才能下载任何文件。
添加回答
举报