从 Spring Boot REST 服务下载文件
本文解决了从 Spring Boot REST 服务有效下载文件的问题。下面提供的代码尝试促进此功能:
<code class="java">@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); }</code>
但是,在尝试通过浏览器下载文件时,该过程会启动但最终失败。可以探索以下选项来解决此问题:
选项1:利用InputStreamResource
可以使用InputStreamResource来表示InputStream。当其他特定资源实现不适用时,应考虑它。
<code class="java">@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.APPLICATION_OCTET_STREAM) .body(resource); }</code>
选项 2:使用 ByteArrayResource
根据 InputStreamResource 文档的建议,ByteArrayResource也可以就业。
<code class="java">@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.APPLICATION_OCTET_STREAM) .body(resource); }</code>
以上是如何从 Spring Boot REST 服务下载文件:为什么 InputStreamReader 失败以及如何使用 InputStreamResource 或 ByteArrayResource 修复它?的详细内容。更多信息请关注PHP中文网其他相关文章!