Download file using angular 2 and web API

Viewed 12438

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;
        });
}
1 Answers
Related