2 回答

TA貢獻(xiàn)1982條經(jīng)驗(yàn) 獲得超2個(gè)贊
您可以在響應(yīng)的輸出流中寫(xiě)入數(shù)據(jù)。
@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貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以嘗試以下代碼。
@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);
}
您必須設(shè)置為 Application Octet Stream 才能下載任何文件。
添加回答
舉報(bào)