首页 > 解决方案 > 使用springboot和angular下载文件

问题描述

我使用角度和弹簧,我正在尝试下载文件。

我只能使用 spring('http://localhost:8080/download) 下载文件,但我不知道如何将它与 angular 连接。对于春天,我正在使用 ResponseEntitiy 这是代码

 @GetMapping(value ="/download")
    public ResponseEntity<Object> downloadFile() throws IOException, PropertyException, JAXBException
    {
        bookListService.convertBookListToXml();
        return bookListService.downloadXml();
        
    }; 

和服务

public ResponseEntity<Object> downloadXml() throws FileNotFoundException {
    String filename = "booksExport.xml";
    File file = new File(filename);
    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition",
            String.format("attachment; filename=\"%s\"", file.getName()));
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
    ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.parseMediaType("application/txt")).body(resource);
    return responseEntity;
}

我尝试了许多选项来将响应与角度联系起来,但没有一个有效。ResponseEntity 甚至是好的回报吗?

角度目前是
html

<button class="btn btn-primary" style="margin-left: 10px" (click)="downloadFile2()">download File</button>

组件.ts

  downloadFile2() {
    this.fileDownloadService.downloadFile3();
  }

和服务

  downloadFile3(): any {
        return this.http.get('http://localhost:8080/download');
  }

标签: angularspring

解决方案


对于 ResponseEntity,使用 InputStreamResource 类型,在头部添加信息并在正文中传递文件,如下所示:

public ResponseEntity<InputStreamResource> viewCheckExcel() throws JRException, IOException {
    ByteArrayInputStream in = service.generateFile();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", "attachment; filename=customers.xlsx");
 return ResponseEntity
              .ok()
              .headers(headers)
              .body(new InputStreamResource(in));
}

这适用于文件 Excel,但结构相同。

要在服务中转换 ByteArrayInputStream 中的文件,您可以这样做:

File file = new File(wfc.getPathExcel()+"/customer.xlsx");
return new ByteArrayInputStream(Files.readAllBytes(file.toPath()));

注意:在 FrontEnd 的方法中指定接收的文件类型。


推荐阅读