使用angular 2和web API下载文件

时间:2017-08-02 12:51:46

标签: angular asp.net-web-api

我有Angular 4和Web API应用程序,我正在尝试使用Web API和typescript Blob下载文件。以下是两者的代码示例。 当我点击下载按钮时,一个帖子请求被发送到Web API,作为响应发送文件流,typescript将此流转换为图像。但是,当我打开此图片时,它会向我显示错误 - "我们无法打开此文件"。

代码 - : Web API

    public HttpResponseMessage Download()
    {
        string strFileUrl = "some absolute path";

        if (strFileUrl != "")
        {
            FileInfo file = new FileInfo(strFileUrl);

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);


            var stream = new FileStream(file.FullName, FileMode.Open);
            response.Content = new StreamContent(stream);
        //  response.Content = new ByteArrayContent(CommonUtil.FileToByteArray(file.FullName));
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(CommonUtil.GetContentType(file.Extension.ToLower()));
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
                FileName = file.Name
            };
            response.Content.Headers.ContentDisposition.FileName = file.Name;
            response.Content.Headers.ContentLength = file.Length;
            response.Headers.Add("fileName", file.Name);

            return response;
        }
        return new HttpResponseMessage(HttpStatusCode.NotFound);
    }

Angular Component.ts -

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));
}

Service.ts -

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;
        });
}

1 个答案:

答案 0 :(得分:2)

我在从流创建docx文件时遇到了类似的问题,我最终这样做了:

Service.ts:

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

Component.ts:

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();
    }
  });
}