首頁 > Java > java教程 > 主體

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

Mary-Kate Olsen
發布: 2024-10-28 04:40:01
原創
446 人瀏覽過

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

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