使用angular 2和web API下载文件

使用angular 2和web API下载文件,angular,asp.net-web-api,Angular,Asp.net Web Api,我有Angular 4和web API应用程序,我正在尝试使用web API和typescript Blob下载文件。下面是两者的代码示例。 当我点击下载按钮时,一个post请求被发送到web API,作为对发送文件流的响应,typescript将该流转换为图像。但当我打开这张图片时,它显示了下面的错误——“我们无法打开此文件” 代码-: Web API 角分量- private OnImageDownloadClick() { this.uploadServiceRef.Downloa

我有Angular 4和web API应用程序,我正在尝试使用web API和typescript Blob下载文件。下面是两者的代码示例。 当我点击下载按钮时,一个post请求被发送到web API,作为对发送文件流的响应,typescript将该流转换为图像。但当我打开这张图片时,它显示了下面的错误——“我们无法打开此文件”

代码-: Web API

角分量-

private OnImageDownloadClick()
{
    this.uploadServiceRef.DownloadFile(path).subscribe(x => {

    //  method 1
        let head = x.headers.get("Content-Type");
        let fileName = x.headers.get("fileName");
        this.fileSaverServiceRef.save(x, fileName, head);

        OR

    //  method 2
        let head = x.headers.get("Content-Type");
        var blob = new Blob([x.arrayBuffer], { type: head });

        var fileURL = URL.createObjectURL(blob);
        window.open(fileURL);
    },
    error => console.log(error));
}
服务台-

public DownloadFile(path): Observable<any> {
    let obj: any = {
        path: path
    }
    this.headers = new Headers();
    this.headers.append('Content-Type', 'application/json');
    this.headers.append('responseType', ResponseContentType.Blob);

    return this.http.request(DOWNLOAD_DOCUMENT_URL, RequestMethod.Post, this.headers, obj)
        .map((x) => {
            return x;
        });
}
公共下载文件(路径):可观察{
设obj:any={
路径:路径
}
this.headers=新的headers();
this.headers.append('Content-Type','application/json');
this.headers.append('responseType',ResponseContentType.Blob);
返回this.http.request(下载\u文档\u URL,RequestMethod.Post,this.headers,obj)
.map((x)=>{
返回x;
});
}

我在从stream创建docx文件时遇到了类似的问题,最后我做了以下工作:

Service.ts:

postAndGetResponse(myParams){
  return this._http.post(this.api, {myParams}, {responseType: ResponseContentType.Blob})
  .map(response => (<Response>response).blob())
  .catch(this.handleError);
}

也许你正在搜索的是这个解决方案:已经尝试过这个解决方案,但是它下载了一个空白文件,这个怎么样。。。您可能会发现此链接也很有用…-因为我没有发现您在哪里指定了要下载的文件类型(BLOB除外),所以我尝试了这段代码,但我下载了
BLOB(3169){size:3169,键入:“application/vnd.openxmlformats of icedocument.wordprocessingml.document”}
文件,其中包含一些file.xml。不是真正的文本。你能给我提出解决办法吗?喜欢
postAndGetResponse(myParams){
  return this._http.post(this.api, {myParams}, {responseType: ResponseContentType.Blob})
  .map(response => (<Response>response).blob())
  .catch(this.handleError);
}
downloadFile(){
  this.service.postAndGetResponse(myParams).subscribe(response => {
    var fileName = "nameForFile" + ".extension";
    if(window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(response, fileName);
    }else{
      var link = document.createElement('a');
      link.setAttribute("type", "hidden");
      link.download = fileName;
      link.href = window.URL.createObjectURL(response);
      document.body.appendChild(link);
      link.click();
    }
  });
}