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

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

Barbara Streisand
Barbara Streisand原創
2024-10-27 17:47:31162瀏覽

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn