我正在尝试使用React前端下载文件,但是控制器中的方法无法下载
该方法之所以有效,是因为它不会启动任何异常并且字节数组也有效,但是当我关闭流时,下载不会发生
public void downloadFile(@PathVariable("numeroOfferta") String numeroOfferta, @RequestParam(value="file") String file, HttpServletResponse response, HttpServletRequest req) throws IOException {
String filePathToBeServed =
File fileToDownload = new File(filePathToBeServed + file);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename="+file);
response.setStatus(HttpServletResponse.SC_OK);
try(FileInputStream in = new FileInputStream(fileToDownload);
OutputStream out = response.getOutputStream()) {
byte[] buffer = new byte[4096];
while ((in.read(buffer, 0, 4096)) != -1) {
out.write(buffer, 0, 4096);
}
out.flush();
out.close();
in.close();
}
NumeroOfferta只是一个字符串,我需要将其放入文件夹中,并且文件包含我从网页发送的文件的名称。
尽管方法可行,但我不明白为什么它不下载我选择的文件。谢谢您的回答
答案 0 :(得分:0)
只需使用Spring MVC ResponseEntity:
public void downloadFile(@PathVariable("numeroOfferta") String numeroOfferta,
@RequestParam(value="file") String file) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData(file, file);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
byte[] content = Files.readAllBytes(new File(filePathToBeServed + file).toPath());
return new ResponseEntity(content, headers, HttpStatus.OK);
}
就是这样。