儘管瀏覽器啟動了這個過程,但為什麼我的 Spring Boot REST 服務下載會失敗?
Oct 27, 2024 pm 05:47 PM從Spring Boot Rest 服務下載檔:下載失敗故障排除
本文解決了嘗試透過Spring Boot Rest 服務下載檔案時遇到的問題Spring Boot REST 服務。儘管在瀏覽器中啟動了下載,但該過程始終失敗。以下是對問題和潛在解決方案的分析:
服務方法:
提供的程式碼示範了負責下載檔案的服務方法:
<code class="java">@RequestMapping(path="/downloadFile",method=RequestMethod.GET) 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)); return ResponseEntity.ok().headers(headers).contentLength(file2Upload.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(i); }</code>
選項1:利用InputStreamResource
提供的程式碼從檔案建立一個InputStreamReader 並使用ResponseEntity 傳回它。但是,建議使用 spring-core 函式庫中的 InputStreamResource。此實作為串流提供了資源,確保在下載過程中正確處理流程。
<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
Spring 文件建議使用 ByteArrayResource 而不是 InputStreamResource。使用此資源類型涉及將整個文件讀入位元組數組並從中建立資源。這種方法在某些場景下是有優勢的,例如提高小檔案的效能。
<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 實現無縫文件下載休息服務。
以上是儘管瀏覽器啟動了這個過程,但為什麼我的 Spring Boot REST 服務下載會失敗?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱門文章

熱門文章

熱門文章標籤

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

2025年的前4個JavaScript框架:React,Angular,Vue,Svelte

如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?

如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?

Spring Boot Snakeyaml 2.0 CVE-2022-1471問題已修復
