【问题标题】:Send File with SpringBoot to Angular2使用 SpringBoot 将文件发送到 Angular2
【发布时间】:2018-12-27 06:56:00
【问题描述】:

当我在 SpringBoot 中创建一个文件(我可以在我的桌面上获取带有数据的文件)时,我尝试将此文件发送到 Angular2,但是当我的文件到达时,我在 Angular2 中得到 NULL。

SpringBoot:

这里,我打电话给SpringBOOT下载Excel。

@RequestMapping(method = RequestMethod.GET, path = "/{download}", produces = MediaType.APPLICATION_JSON_VALUE)
    public MultipartFile download() {

        MultipartFile myFile = null;
        myFile = downloadExcell();

        return myFile;
    }

在这个函数中我创建了myExcell,我的excell创建成功,我可以在我的桌面获取文件。

private MultipartFile downloadExcell() {
        MultipartFile myFile = null;
        String eyelash = "People";

        try {
            String filename = pathTempdownloadFile;

            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet(eyelash);

            String [] header= {"YEAR","MONTH","NAME","SURNAME","TLF"} ;
            HSSFRow rowhead = sheet.createRow((short) 0);


            for (int i = 0; i < header.length; i++) {
                cell = rowhead.createCell(cellnum);
                cell.setCellValue(header[i]);
                cellnum++;
            }

            FileOutputStream fileOut = new FileOutputStream(filename);
            workbook.write(fileOut);
            fileOut.close();
            workbook.close();

        } catch (Exception ex) {
            System.out.println(ex);
        }

        return myFile;
    }

现在我可以将 fileOut 分配给 myFile

myFile = (MultipartFile) fileOut;

错误 ->

java.lang.ClassCastException: java.io.FileOutputStream cannot be cast to org.springframework.web.multipart.MultipartFile

最后我在 Angular2 myFile 中得到 (false)。

Angular2->

  downloadFile() {
    this.service.downloadFile().subscribe(data => {
      console.log("FILE", data);
    });
  }

 downloadFile() {
     const url = "http://localhost:8080/ml/download";
     return this.http.get(url);
  }

我需要将 Excell 和 SpringBoot 发送到 Angular2,但我不知道该怎么做。 类型

【问题讨论】:

    标签: angular spring-boot


    【解决方案1】:

    你不应该直接从 spring boot 发送文件。这会干扰服务器上的流量。我建议您将文件上传到任何静态文件托管,如 S3。然后将文件的 URL 发送到 angular。让 Angular 从 S3 中获取它。

    【讨论】:

      【解决方案2】:

      正如您已经了解到的,MultipartFileFileOutputStream 是不相关的:从实例化中可以看出,输出流已创建并用于写入文件,而不是您的 servlet 响应,MultipartFile 是通常用作请求参数,但不能用于响应。

      根据您的要求,您可以将 Excel 文件直接写入 Web 请求输出流。但是,我认为最好先将其存储在文件系统中,然后再从那里提供服务。

      为了访问响应,您可以将HttpServletResponse 注入到控制器方法中(Spring 会注意正确填充此参数):

      public void download(HttpServletResponse response)

      另外请注意,我已将返回类型更改为 void,因为您将只使用 response 参数。

      存储文件后,您现在可以将其写入响应。请记住将正确的内容类型设置为响应的一部分,以便请求客户端,例如浏览器,知道如何处理它。

          response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
          response.setHeader("Content-disposition", "attachment; filename=result.xlsx");
          try (final InputStream is = new FileInputStream(filename)) {
              IOUtils.copy(is, response.getOutputStream());
              response.flushBuffer();
          } catch (Exception ex) {
              // deal with error, e.g. response.setStatus(500) to signal an internal server error
          }
      

      请注意,我使用了 Apache Commons IO 库中的 IOUtils.copy。它只是将输入字节从FileInputStream 复制到响应OutputStream,您也可以手动实现:

          byte[] buffer = new byte[4096];
          OutputStream os = response.getOutputStream();
          for (long count = 0L; -1 != (n = is.read(buffer)); count += (long)n) {
              os.write(buffer, 0, n);
          }
      

      另外请注意,我指定了另一个标题 Content-Disposition。这为浏览器如何处理接收到的文件提供了额外的指导; attachment 通常会导致一个保存对话框,而inline 会产生文件的内联显示(有趣,例如对于 PDF)。浏览器将使用指定的文件名来存储文件。

      【讨论】:

      • @EduBw 如果对您有帮助,如果您将我的回复标记为正确,我将不胜感激。如果您需要更多指导,请随时添加其他问题。
      • 最后我不得不在响应中添加标题,但是谢谢
      猜你喜欢
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 2019-09-25
      • 1970-01-01
      相关资源
      最近更新 更多