首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >StreamingResponseBody正在返回空文件

StreamingResponseBody正在返回空文件
EN

Stack Overflow用户
提问于 2019-05-26 20:57:30
回答 1查看 1.8K关注 0票数 2

我正在尝试创建一个rest服务,使用Springboot从存储库中下载文件。

我试图返回一个带有StreamingResponseBody的ResponseEntity,将我从存储库中获得的文件作为InputStream返回。

这是我目前拥有的代码:

代码语言:javascript
复制
@GetMapping(path = "/downloadFile")
    public ResponseEntity<StreamingResponseBody> downloadFile(@RequestParam(value = "documentId") String documentId,
            HttpServletRequest request, HttpServletResponse response) throws InterruptedException, IOException {

        InputStream is = downloadService.getDocument(documentId);

        StreamingResponseBody out = outputStream -> {

            outputStream.write(IOUtils.toByteArray(is));
        };

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "text/csv");
        headers.add("Content-Disposition", "attachment; filename=" + documentId);
        headers.add("Pragma", "no-cache");
        headers.add("Cache-Control", "no-cache");

        return (new ResponseEntity<>(out, headers, HttpStatus.OK));

    }

当我直接使用浏览器或邮递员使用此端点时,下载的文件为空。我知道OutputStream是异步写入的(异步是在config类中启用的)。

如何使用此服务并将文件完全写入我正在使用的存储库?(如果可能,使用Postman,仅用于测试目的)

我是否正确地构建了服务?

EN

回答 1

Stack Overflow用户

发布于 2019-05-27 02:36:08

我稍微修改了一下代码,在我的documentId中是要下载的文件的名称。我测试过了,它工作得很好。检查下面的代码。

代码语言:javascript
复制
@GetMapping(path = "/downloadFile")
public ResponseEntity<StreamingResponseBody> downloadFile(
      @RequestParam(value = "documentId") String documentId,
      HttpServletRequest request,
      HttpServletResponse response)
      throws InterruptedException, IOException {
    String dirPath = "E:/sure-delete/"; //Directory having the files
    InputStream inputStream = new FileInputStream(new File(dirPath + documentId));
    final StreamingResponseBody out =
        outputStream -> {
          int nRead;
          byte[] data = new byte[1024];
          while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            System.out.println("Writing some bytes of file...");
            outputStream.write(data, 0, nRead);
          }
        };
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "text/csv");
    headers.add("Content-Disposition", "attachment; filename=" + documentId);
    headers.add("Pragma", "no-cache");
    headers.add("Cache-Control", "no-cache");
    return ResponseEntity.ok().headers(headers).body(out);
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56313714

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档