使用 SpringBoot 将文件发送到 Angular2 [英] Send File with SpringBoot to Angular2

查看:36
本文介绍了使用 SpringBoot 将文件发送到 Angular2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I created a File in SpringBoot (I can get File with data in my desktop) I am tryied send this File to Angular2 but When my File arrive , I get NULL in Angular2.

SpringBoot:

SpringBoot:

这里,我调用 SpringBOOT 下载 Excell.

Here, I call to SpringBOOT for download Excell.

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

        MultipartFile myFile = null;
        myFile = downloadExcell();

        return myFile;
    }

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

In this function I created myExcell ,My excell is created success, I can get file in my desktop.

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

Now I have that to assign fileOut to myFile

myFile = (MultipartFile) fileOut;

错误 ->

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

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

Finally I get (false) in Angular2 myFile.

Angular2->

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

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

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

I need send the Excell the SpringBoot to Angular2, but I don't found how do. Ty

推荐答案

正如你已经知道的,MultipartFileFileOutputStream 是无关的:正如你从实例化中看到的,输出流被创建并用于写入文件,而不是写入您的 servlet 响应,并且 MultipartFile 通常用作请求参数但不能用于响应.

As you already learned, MultipartFile and FileOutputStream are unrelated: as you can see from the instantiation, the output stream was created and used to write to a file, not to your servlet response, and MultipartFile is usually used as a request parameter but can't be used for the response.

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

Depending on you requirements, you could write the Excel file directly to the web requests output stream. However, I believe it is good practice to store it in the file system first and then serve it from there.

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

In order to access the response, you can inject the HttpServletResponse into the controller method (Spring takes care to fill this parameter properly):

public void download(HttpServletResponse response)

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

Also note that I've changed the return type to void, as you'll be working with the response parameter only.

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

After storing your file, you can now write it to the response. Remember to set the proper content type as part of the response, so that the requesting client, e.g. the browser, knows how to deal with it.

    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,您也可以手动实现:

Note that I've used IOUtils.copy from the Apache Commons IO library. It simply copies input bytes from the FileInputStream to the response OutputStream, you can implement this manually as well:

    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).浏览器将使用指定的文件名来存储文件.

Also note that I've specified another header, Content-Disposition. This provides additional guidance for the browser on how to deal with the received file; attachment usually leads to a save dialog, while inline produces an inline display of the file (interesting e.g. for PDFs). The specified filename will be used by the browser to store the file.

这篇关于使用 SpringBoot 将文件发送到 Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆