【问题标题】:Downloading an excel file in angular client (angular v5.2) received as a response from WebAPI在 Angular 客户端(Angular v5.2)中下载 excel 文件作为 WebAPI 的响应
【发布时间】:2018-05-03 18:42:55
【问题描述】:

我有以下服务允许我使用 http Get 下载文件

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { saveAs } from 'file-saver';

@Injectable()
export class FileService {

  blob: Blob;
  url: string;

  constructor(private _http: Http) { }

  uploadFile(file: File, filetype: string) {
    console.log('uploading...');
    const endpoint = 'http://localhost:60994/api/file';
    const formData:  FormData = new FormData();
    formData.append(filetype, file, file.name);
    return this._http.post(endpoint, formData);
  }

  getFile() {
    return this._http.get('http://localhost:60994/api/file')
    .subscribe(data => {
      if (data != null)
      {
        this.blob = new Blob([data._body], { type: 'application/vnd.ms-excel' });
        const file = new File([this.blob], 'report.xlsx', { type: 'application/vnd.ms-excel' });
        console.log(this.blob);
        console.log(file);
        this.url = window.URL.createObjectURL(file);
        window.open(this.url);
      }
    });
  }
}

下载的文件(xlsx,xls) 大部分是损坏的,没有数据(服务器发送的文件有数据,我自己检查过)。还有,

console.log(this.blob);

console.log(file); 

显示文件大小几乎与服务器预期的文件大小完全相同(在 chrome 的控制台中)。

我的最佳猜测是,我在重建接收到的文件时出错了。

【问题讨论】:

标签: angular asp.net-web-api httprequest angular5 httpresponse


【解决方案1】:

您的 http GET 请求很可能需要一些选项来表明您对原始响应字节感兴趣:

this._http.get(url, {responseType: 'blob'}).subscribe(..)

我不确定当前调用的 'TRIAL_PRICE' 参数是什么,但这肯定不是 angular5 HTTP 客户端所期望的参数:

通过将 responseType 设置为 blob 进行调用,您还将获得一个 Blob 对象作为 Observable 有效负载,因此您也不需要正文转换逻辑。

【讨论】:

  • 所以@Chris,我发现 Angular 5 使用的是 HttpClient 导入而不是 import { Http } from '@angular/http';
【解决方案2】:

原来我为 HTTP GET 使用了错误的导入 (Http)。

导入import { HttpClient } from '@angular/common/http';并更改

 getFile() {
        return this._http.get('http://localhost:60994/api/file',{responseType: 'blob'})
        .subscribe(data => saveAs(data));
      }

【讨论】:

    猜你喜欢
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    • 2013-11-02
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2021-04-12
    相关资源
    最近更新 更多