Akash Shelke
Akash Shelke

Reputation: 41

Download file using angular 2 and web API

I have Angular 4 and web API application, I am trying to download file using Web API and typescript Blob. Below is the code sample of both. When I click on download button a post request is sent to web API which in response send file stream, typescript converts this stream to image. But when I opens this image it shows me below error - "We can't open this file".

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

Upvotes: 4

Views: 12789

Answers (1)

Dalcof
Dalcof

Reputation: 164

I had a similar issue in creating a docx file from stream and I ended up doing this:

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

Upvotes: 3

Related Questions