首页 > Java > java教程 > 正文

如何从 Spring Boot REST 服务成功下载文件?

Barbara Streisand
发布: 2024-10-28 07:53:02
原创
927 人浏览过

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!