4

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;
        });
}
Akash Shelke
  • 41
  • 1
  • 1
  • 2
  • Maybe what you are searching for ist this solution: https://stackoverflow.com/questions/44871600/download-file-sent-in-response-angular2 – Ludwig Aug 02 '17 at 12:58
  • Already tried this solution but it downloads blank file – Akash Shelke Aug 02 '17 at 13:03
  • How about this one... https://stackoverflow.com/questions/35138424/how-do-i-download-a-file-with-angular2 – JGFMK Aug 02 '17 at 18:39
  • You might find this link useful too... https://www.iana.org/assignments/media-types/media-types.xhtml - since I didn't spot where you indicated type of file you are downloading (other than BLOB). – JGFMK Aug 02 '17 at 18:41

1 Answers1

3

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();
    }
  });
}
Dalcof
  • 166
  • 7
  • I tried this code, but for me download `Blob(3169) {size: 3169, type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}` file that have inside some file.xml. Not real text. Can you suggest me any solution? Like in https://stackoverflow.com/questions/50016568/how-to-manage-responsetype-blob-using-angular5-in-front-end – OnnaB Apr 25 '18 at 08:43