首页  >  文章  >  Java  >  尽管浏览器启动了该过程,但为什么我的 Spring Boot REST 服务下载失败?

尽管浏览器启动了该过程,但为什么我的 Spring Boot REST 服务下载失败?

Barbara Streisand
Barbara Streisand原创
2024-10-27 17:47:31162浏览

 Why is my Spring Boot REST service download failing, despite the browser initiating the process?

从 Spring Boot Rest 服务下载文件:下载失败故障排除

本文解决了尝试通过 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 {
    File file2Upload = new File("C:\Users\admin\Desktop\bkp\1.rtf");
    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

提供的代码从文件创建一个 InputStreamReader 并使用 ResponseEntity 返回它。但是,建议使用 spring-core 库中的 InputStreamResource。此实现为流提供了资源,确保在下载过程中正确处理流。

<code class="java">@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {
    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

Spring 文档建议使用 ByteArrayResource 而不是 InputStreamResource。使用此资源类型涉及将整个文件读入字节数组并从中创建资源。这种方法在某些场景下是有优势的,例如提高小文件的性能。

<code class="java">@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {
    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 实现无缝文件下载休息服务。

以上是尽管浏览器启动了该过程,但为什么我的 Spring Boot REST 服务下载失败?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn