【问题标题】:Angular-SpringBoot downlod excel file HttpErrorResponseAngular-Spring Boot下载excel文件HttpErrorResponse
【发布时间】:2019-12-03 18:43:26
【问题描述】:

我正在使用带有角度首页的 Spring Boot 服务器。我有一项服务可以从我的前面下载.xlsx 文件。

这是我的代码: 服务器端代码:

 @GetMapping("/ExportExcel{date}")
 public ResponseEntity<InputStreamResource> excelExportReport(@RequestParam Date date) throws IOException {

List<InterfaceTable> interfaceTables=interfaceTableRepo.afficheAHT(date);
       ByteArrayInputStream in =ExportExcel.ahtToExcel(interfaceTables);
       HttpHeaders headers = new HttpHeaders();
       headers.add("Content-Disposition", "attachment; filename=customers.xlsx");

return ResponseEntity
             .ok()
             .headers(headers)
             .body(new InputStreamResource(in));      

}
角服务:

 ExportExcel(date:string){
 return this.http.get<Operation[]>(this.exportUrl+date) }

问题是我在角度方面得到了HttpErrorResponse,即使它:

错误:SyntaxError: JSON.parse () 中 JSON.parse () 的位置 0 中的意外标记 P 在 ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:3240:31) 在 Object` 的 XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:9948:51)

【问题讨论】:

    标签: angular typescript spring-boot spring-mvc httpclient


    【解决方案1】:

    弹簧控制器

     @GetMapping("/ExportExcel/{date}")
     public void excelExportReport(@RequestParam Date date, HttpServletResponse httpServletResponse) throws IOException {
    
               List<InterfaceTable> interfaceTables=interfaceTableRepo.afficheAHT(date);
               ByteArrayInputStream in =ExportExcel.ahtToExcel(interfaceTables);
               byte[] byteArray = new byte[in.available()];
               try {
                   byteArrayInputStream.read(byteArray);
               } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
               }
    
               ByteArrayOutputStream out = new ByteArrayOutputStream(byteArray.length);
               out.write(byteArray, 0, byteArray.length);
    
               httpServletResponse.setContentType("text/csv");
               httpServletResponse.addHeader("Content-Disposition", "attachment; filename=customers.csv");
    
               OutputStream os;
               try {
                   os = httpServletResponse.getOutputStream();
                   out.writeTo(os);
                   os.flush();
                   os.close();
               } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
               }
        }
    

    前端服务

    return this.http.get("/ExportExcel/", this.commonRepository.getRequestOptionsForCSV(URL.BEARER)).map(res => {
              return {
                  filename: 'customers.csv',
                  data: res.blob()
                };
    });
    

    前端组件

    this.customerService.generateReportCsv(this.receiptReportPage.value).subscribe((results)=>{
        console.log(results);
    
        var url = window.URL.createObjectURL(results.data);
    
        var a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display: none');
        a.setAttribute('target', 'blank');
        a.href = url;
        a.download = results.filename;
        a.click();
        window.URL.revokeObjectURL(url);
        a.remove();
    });
    

    【讨论】:

      【解决方案2】:

      对于初学者:默认情况下,Angular 期望响应为application/json。您需要对其进行更改,以便正确解析它。通常用于传输文件,它将是blob

      然后您可以使用任何库来转换此 blob 并将其保存为文件。我更喜欢使用“文件保护程序”。

      角度方面的代码如下所示:

      this.http.get(url,{ observe: 'response', responseType: 'blob' }).subscribe(res => { 
          const blob = new Blob([res.body], { type: 'application/vnd.ms-excel' });
          FileSaver.saveAs(blob, 'report.xls');
      });
      

      【讨论】:

      • 我更改了代码,但出现 CORS 策略错误和 Unknown HttpErrorResponse 。
      • 您需要在后端启用 CORS。对于 spring-boot,将 @CrossOrigin 添加到您的控制器类。
      • 我的控制器类中有@CrossOrigin
      猜你喜欢
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-09
      相关资源
      最近更新 更多