我正在嘗試使用.Net核心web api使用angular 2下載PDF(以及word,excel和image)文件。我在這裏粘貼了一些代碼示例,下載該文件,但是當我嘗試打開下載的文件時,它會給我帶來損壞的文件。使用angular 2和.net核心webapi下載PDF文件
這裏是我的.NET的核心Web API代碼
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;
}
我也曾嘗試另一個代碼示例
public FileResult TestDownload(int id)
{
HttpContext.Response.ContentType = "application/pdf";
FileContentResult result = new FileContentResult(myArray, "application/pdf")
{
FileDownloadName = "test.pdf"
};
return result;
}
這是我在角服務
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.myService.getTestPdfFile()
.subscribe(blob => {
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Test.pdf";
link.click();
}, error => {});
}
感謝。我發現了答案。 – Jay