首頁 > Java > java教程 > 主體

儘管瀏覽器啟動了這個過程,但為什麼我的 Spring Boot REST 服務下載會失敗?

Barbara Streisand
發布: 2024-10-27 17:47:31
原創
160 人瀏覽過

 Why is my Spring Boot REST service download failing, despite the browser initiating the process?

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

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!