首页  >  文章  >  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

根据 InputStreamResource 文档的建议,使用 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