Download PDF file, Angular 6 and Web API

Madhu picture Madhu · Aug 1, 2018 · Viewed 28.8k times · Source

I want to download PDF using Angular 6 and Web API. Here is the code implementation,

mycomponent.ts

download(myObj: any) {
    this.testService.downloadDoc(myObj.id).subscribe(result => {

        var url = window.URL.createObjectURL(result);
        window.open(url);
        console.log("download result ", result);
    });
}

myService.ts

downloadDoc(Id: string): Observable<any> {
    let url = this.apiUrl + "api/myApi/download/" + Id;
    return this.http.get(url, { responseType: "blob" });
}

Web API Service

[HttpGet("download/{DocId}")]
    public async Task<HttpResponseMessage> GetDocument(string docId)
    {
        var docDetails = await _hoaDocs.GetDocumentDetails(docId).ConfigureAwait(false);
        var dataBytes = docDetails.Stream;
        var dataStream = new MemoryStream(dataBytes);

        var response = new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.OK,
            Content = new StreamContent(dataStream)
        };

        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = docDetails.File_Name
        };
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

        return response;
    }

When I execute the above code, it is not downloading the PDF, here is the result object that is logged in the console

download result  
Blob(379) {size: 379, type: "application/json"}
size:379
type:"application/json"
__proto__:Blob

Answer

r2018 picture r2018 · Aug 5, 2018

I am assuming you are using .Net Core.

You return type is HttpResponseMessage. For .Net Core onward, it should be IActionResult.

So, in your case, you will be returning

return File(<filepath-or-stream>, <content-type>)

Or

You have to make one small change in your Startup.cs file:

services.AddMvc().AddWebApiConventions();

Then, I am not 100% sure here, but you have to change the routing too:

routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");