DaR*_*oGa 20 pdf filestream asp.net-web-api angular
我有一个带有ASP.Net Web API的angular2项目.我有代码从我的数据库中检索文件路径,该文件路径转到我服务器上的文档.然后,我想在浏览器中的新选项卡中显示此文档.有没有人有任何建议怎么做?
我很高兴在Angular2(Typescript)或我的API中检索文件并将其流式传输.
这是我尝试在我的API中检索它但我无法弄清楚如何在Angular2中接收它并正确显示它:
public HttpResponseMessage GetSOP(string partnum, string description)
{
var sopPath = _uow.EpicorService.GetSOP(partnum, description).Path;
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(sopPath, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
return result;
}
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激.
非常感谢!!!
Ste*_*ota 39
首先,您需要为http请求设置选项 - 设置responseType为ResponseContentType.Blob,用于blob()读取响应blob,并将其类型设置为application/pdf:
downloadPDF(): any {
return this._http.get(url, { responseType: ResponseContentType.Blob }).map(
(res) => {
return new Blob([res.blob()], { type: 'application/pdf' })
}
}
Run Code Online (Sandbox Code Playgroud)
然后,为了获取文件,您需要subscribe创建新文件,并且可以在新标签中创建新文件ObjectURL并使用它window.open()来打开PDF:
this.myService.downloadPDF().subscribe(
(res) => {
var fileURL = URL.createObjectURL(res);
window.open(fileURL);
}
);
Run Code Online (Sandbox Code Playgroud)
jon*_*nas 14
Angular v.5.2.1回答:
在 *.services.ts
downloadPDF(): any {
return this._httpClient.get(url, { responseType: 'blob'})
.map(res => {
return new Blob([res], { type: 'application/pdf', });
});
}
Run Code Online (Sandbox Code Playgroud)
然后在 *.component.ts
downloadPDF() {
let tab = window.open();
this._getPdfService
.downloadPDF()
.subscribe(data => {
const fileUrl = URL.createObjectURL(data);
tab.location.href = fileUrl;
});
}
Run Code Online (Sandbox Code Playgroud)
在调用服务之前启动和打开新选项卡很重要.然后将此选项卡URL设置为fileurl.
角度5
我遇到了同样的问题,我为此失去了几天。
在这里,我的回答可能会对其他人有所帮助,这有助于呈现pdf。
对我来说,即使我提到responseType:'arraybuffer',也无法接受。
为此,您需要提及responseType:'arraybuffer'为'json'。(参考)
工作代码
服务
downloadPDF(): any {
return this._httpClient.get(url, { responseType: 'blob' as 'json' })
.map(res => {
return new Blob([res], { type: 'application/pdf', });
});
Run Code Online (Sandbox Code Playgroud)
}
component.ts
this.myService.downloadPDF().subscribe(
(res) => {
var fileURL = URL.createObjectURL(res);
window.open(fileURL);
}
);
Run Code Online (Sandbox Code Playgroud)
从以下链接引用
https://github.com/angular/angular/issues/18586
| 归档时间: |
|
| 查看次数: |
34254 次 |
| 最近记录: |