I am trying to download PDF (and later word,excel and image) file using angular 2 with .Net core web api. I have pasted some code sample here which downloads the file but when I try to open the downloaded file, it gives me corrupted file.
Here is my .net core web api code
public HttpResponseMessage GetTestPdfFile()
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(myArray); //byte[] myArray is byte[] of file downloaded from Azure blob
//response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("inline");
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = myFileName;
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
return response;
}
I have also tried another code sample
public FileResult TestDownload(int id)
{
HttpContext.Response.ContentType = "application/pdf";
FileContentResult result = new FileContentResult(myArray, "application/pdf")
{
FileDownloadName = "test.pdf"
};
return result;
}
This is what I have in angular service
getTestPdfFile(): Observable<any> {
let url = 'API_URL'
let headers1 = new Headers();
headers1.append('Content-Type', 'application/pdf');
headers1.append('responseType', 'arrayBuffer');
return this.http.get(url, {headers: headers1})
.map(res => {
var contentType = 'application/pdf';
var blob = new Blob([res.arrayBuffer()], { type: contentType });
return blob;
})
}
This is how I am subscribing to obsevable
this.myService.getTestPdfFile()
.subscribe(blob => {
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Test.pdf";
link.click();
}, error => {});
}
Users can either left-click a download link to download the file or right-click the link to choose “ Save Link As ” in the context menu and save the file.
I had to change my angular service to below and all worked fine
getTestPdfFile(): Observable<any> {
let url = 'API_URL'
return this.http.get(url, { responseType: ResponseContentType.Blob })
.map(res => res.blob())
.catch(this.handleError)
}
I am using this as my web api
public FileResult TestDownload(int id)
{
HttpContext.Response.ContentType = "application/pdf";
FileContentResult result = new FileContentResult(myArray, "application/pdf")
{
FileDownloadName = "test.pdf"
};
return result;
}
I've never had luck downloading items using observables. What I've done instead is use window.open("http://urlToDocument.Test.pdf", "_blank")
. This will download or prompt to download the file in a new tab.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With