【问题标题】:Downloading files with Angular 2 and .Net Core API使用 Angular 2 和 .Net Core API 下载文件
【发布时间】:2019-02-10 16:21:41
【问题描述】:

我有一个 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);
  }

【问题讨论】:

    标签: angular asp.net-web-api .net-core


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 2017-07-27
    • 1970-01-01
    • 2019-08-24
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多