從 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中文網其他相關文章!