Angular2显示PDF

前端之家收集整理的这篇文章主要介绍了Angular2显示PDF前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个带有ASP.Net Web API的angular2项目.我有代码从我的数据库中检索文件路径,该文件路径转到我服务器上的文档.然后,我想在浏览器中的新选项卡中显示此文档.有没有人有任何建议怎么做?

我很高兴在Angular2(Typescript)或我的API中检索文件并将其流式传输.

这是我尝试在我的API中检索它但我无法弄清楚如何在Angular2中接收它并正确显示它:

  1. public HttpResponseMessage GetSOP(string partnum,string description)
  2. {
  3. var sopPath = _uow.EpicorService.GetSOP(partnum,description).Path;
  4. HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
  5. var stream = new FileStream(sopPath,FileMode.Open);
  6. result.Content = new StreamContent(stream);
  7. result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
  8. return result;
  9. }

任何帮助将不胜感激.

非常感谢!!!

首先,您需要为http请求设置选项 – 将responseType设置为ResponseContentType.Blob,使用blob()将响应读取为blob并将其类型设置为application / pdf:
  1. downloadPDF(): any {
  2. return this._http.get(url,{ responseType: ResponseContentType.Blob }).map(
  3. (res) => {
  4. return new Blob([res.blob()],{ type: 'application/pdf' })
  5. }
  6. }

然后,为了获取文件,您需要订阅它,您可以创建新的ObjectURL并使用window.open()在新选项卡中打开PDF:

  1. this.myService.downloadPDF().subscribe(
  2. (res) => {
  3. var fileURL = URL.createObjectURL(res);
  4. window.open(fileURL);
  5. }
  6. );

猜你在找的Angularjs相关文章