我正在尝试从Spring Boot Rest服务下载文件。
@RequestMapping(path="/downloadFile",method=RequestMethod.GET) @Consumes(MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<InputStreamReader> downloadDocument( String acquistionId, String fileType, Integer expressVfId) throws IOException { File file2Upload = new File("C:\\Users\\admin\\Desktop\\bkp\\1.rtf"); HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); InputStreamReader i = new InputStreamReader(new FileInputStream(file2Upload)); System.out.println("The length of the file is : "+file2Upload.length()); return ResponseEntity.ok().headers(headers).contentLength(file2Upload.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(i); }
当我尝试从浏览器下载文件时,它开始下载,但始终失败。服务有什么问题导致下载失败?
仅当没有其他特定的资源实现适用时才应使用。特别是,尽可能选择ByteArrayResource或任何基于文件的Resource实现。
@RequestMapping(path = "/download", method = RequestMethod.GET) public ResponseEntity<Resource> download(String param) throws IOException { // ... InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); return ResponseEntity.ok() .headers(headers) .contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(resource); }
Option2作为InputStreamResource的文档建议-使用ByteArrayResource:
@RequestMapping(path = "/download", method = RequestMethod.GET) public ResponseEntity<Resource> download(String param) throws IOException { // ... Path path = Paths.get(file.getAbsolutePath()); ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path)); return ResponseEntity.ok() .headers(headers) .contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(resource); }