Jay*_*Jay 5 asp.net-web-api .net-core angular
我正在尝试使用带有.Net核心web api的角度2下载PDF(以及后来的单词,excel和图像)文件.我已经粘贴了一些下载文件的代码示例,但是当我尝试打开下载的文件时,它会给我一个损坏的文件.
这是我的.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;
}
Run Code Online (Sandbox Code Playgroud)
我还尝试了另一个代码示例
public FileResult TestDownload(int id)
{
HttpContext.Response.ContentType = "application/pdf";
FileContentResult result = new FileContentResult(myArray, "application/pdf")
{
FileDownloadName = "test.pdf"
};
return result;
}
Run Code Online (Sandbox Code Playgroud)
这就是我在角度服务中所拥有的
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;
})
}
Run Code Online (Sandbox Code Playgroud)
这就是我订阅obsevable的方式
this.myService.getTestPdfFile()
.subscribe(blob => {
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Test.pdf";
link.click();
}, error => {});
}
Run Code Online (Sandbox Code Playgroud)
我不得不改变我的角度服务到下面,一切都很好
getTestPdfFile(): Observable<any> {
let url = 'API_URL'
return this.http.get(url, { responseType: ResponseContentType.Blob })
.map(res => res.blob())
.catch(this.handleError)
}
Run Code Online (Sandbox Code Playgroud)
我使用它作为我的web api
public FileResult TestDownload(int id)
{
HttpContext.Response.ContentType = "application/pdf";
FileContentResult result = new FileContentResult(myArray, "application/pdf")
{
FileDownloadName = "test.pdf"
};
return result;
}
Run Code Online (Sandbox Code Playgroud)
我从来没有运气使用可观察量下载项目。我所做的是使用window.open("http://urlToDocument.Test.pdf", "_blank"). 这将在新选项卡中下载或提示下载文件。
| 归档时间: |
|
| 查看次数: |
5620 次 |
| 最近记录: |