我有一个带有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;
- }
任何帮助将不胜感激.
非常感谢!!!
首先,您需要为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' })
- }
- }
然后,为了获取文件,您需要订阅它,您可以创建新的ObjectURL并使用window.open()在新选项卡中打开PDF:
- this.myService.downloadPDF().subscribe(
- (res) => {
- var fileURL = URL.createObjectURL(res);
- window.open(fileURL);
- }
- );