首頁  >  文章  >  Java  >  如何從 Spring Boot REST 服務成功下載檔案?

如何從 Spring Boot REST 服務成功下載檔案?

Barbara Streisand
Barbara Streisand原創
2024-10-28 07:53:02919瀏覽

How to Successfully Download Files from a Spring Boot REST Service?

從 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 {
    // Code for file acquisition...

    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

使用InputStreamResource來包裝文件的InputStream:

<code class="java">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

根據中使用文件的建議,Re> ByteArrayResource 可能更有效率:

<code class="java">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 REST 服務成功下載檔案。

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

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