首页 > 解决方案 > 使用 Angular 2 和 .Net Core API 下载文件

问题描述

我有一个 WebAPI,它有一个制作 Excel 文件并使用File().

在我的 Angular 应用程序中,我订阅了响应并使用 blob 下载文件。但是我在浏览器控制台中收到一个错误,它说它无法解析对 JSON 的响应。

为什么要解析对 JSON 的响应?以及如何解决这个问题?

API 控制器:

 [HttpPost]
 public IActionResult QRGenerator(QRCode qrCode)
 {
      string wwwrootPath = _hostingEnvironment.WebRootPath;

       var QrCodes = new List<QRCode>();
       QrCodes.Add(qrCode);
       ExcelGenerator generator = new ExcelGenerator();
       var fileName = generator.GeneratePrintableSheets(QrCodes, wwwrootPath);
       var path = Path.Combine(wwwrootPath, fileName);
       return DownloadFile(fileName, wwwrootPath);   
  }

  public IActionResult DownloadFile(string fileName, string wwwrootPath)
  {
      var path = Path.Combine(wwwrootPath, fileName);
      var content = System.IO.File.ReadAllBytes(path);
      return File(content, "application/vnd.ms-excel", fileName);
   }

角组件:

  createQR(qrCode: QRCode) {
    let formData: FormData = new FormData();
    this.singleQr.CreateSingleQR(formData).subscribe(data => {
      this.downloadFile(data);
      console.log(data);
    });
  }

 downloadFile(data: any){
   var blob = new Blob([data], { type: 'application/vnd.ms-excel' });
   var url= window.URL.createObjectURL(blob);
   window.open(url);
 }

为了完成,Angular 服务:

 CreateSingleQR(formdata: FormData) {
    return this.http.post(this.qrUrl, formdata);
  }

浏览器错误

标签: angularasp.net-web-api.net-core

解决方案


您需要告诉Angular响应不是JSON,因此它不会尝试解析它。尝试将您的CreateSingleQR代码更改为:

CreateSingleQR(formdata: FormData) {
    return this.http.post(this.qrUrl, formdata, { responseType: ResponseContentType.Blob } );
}

推荐阅读