首頁  >  文章  >  Java  >  如何修復 Spring Boot REST 服務中的檔案下載錯誤?

如何修復 Spring Boot REST 服務中的檔案下載錯誤?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-28 04:40:01445瀏覽

How to Fix File Download Errors in Your Spring Boot REST Service?

解決 Spring Boot Rest 服務中的檔案下載問題

從 Spring Boot REST 服務下載檔案可能會遇到錯誤。為了解決這些問題,我們檢查提供的伺服器端程式碼:

<code class="java">@RequestMapping(path="/downloadFile",method=RequestMethod.GET)
public  ResponseEntity<InputStreamReader> downloadDocument(...) {
    ...
    return ResponseEntity.ok()...body(i);
}</code>

識別問題

問題可能在於使用InputStreamReader,這可能會導致瀏覽器下載失敗。

解決方案選項

  1. 使用InputStreamResource:
<code class="java">@RequestMapping(path="/download",method=RequestMethod.GET)
public ResponseEntity<Resource> download(...) {
    ...
    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
    return ResponseEntity.ok()...body(resource);
}</code>
  1. 使用ByteArrayResource:
<code class="java">@RequestMapping(path="/download",method=RequestMethod.GET)
public ResponseEntity<Resource> download(...) {
    ...
    ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
    return ResponseEntity.ok()...body(resource);
}</code>

實作細節

    InputStreamResource 允許直接使用InputStreamStream,但建議使用不用於大檔案。
  • ByteArrayResource 將整個檔案載入記憶體中,並且更適合小檔案。
透過實作這些解決方案之一,檔案下載應該會從以下位置成功進行: Spring Boot REST 服務。

以上是如何修復 Spring Boot REST 服務中的檔案下載錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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