首页  >  文章  >  Java  >  如何修复 Spring Boot REST 服务中的文件下载错误?

如何修复 Spring Boot REST 服务中的文件下载错误?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-28 04:40:01438浏览

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 允许直接使用 InputStream,但建议使用不用于大文件。
  • ByteArrayResource 将整个文件加载到内存中,并且更适合小文件。

通过实施这些解决方案之一,文件下载应该从以下位置成功进行: Spring Boot REST 服务。

以上是如何修复 Spring Boot REST 服务中的文件下载错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

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