2016-10-28 75 views
13

我有一个带有ASP.Net Web API的angular2项目。我有代码从我的数据库检索到我的服务器上的文档的文件路径。然后我想在浏览器中的新标签中显示这个文档。有没有人有任何建议如何做到这一点?Angular2显示PDF

我很高兴能够检索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; 
    } 

任何帮助将不胜感激。

很多谢谢!

+0

如果您想在另一个选项卡中看到它,为什么不直接打开API的新选项卡并让浏览器解释内容?您可能需要使用MIME类型的“application/pdf”而不是“application/octet-stream”。 – LinuxDisciple

+0

我写了关于获取和显示在Angular 2中的新选项卡中的pdf文件,请查看我的答案:http://stackoverflow.com/questions/37046133/pdf-blob-is-not-showing-content-angular-2/ 39657478#39657478 –

+0

@StefanSvrkota会这样使用我的API,因为它是?或者,我需要进行更改才能以正确的格式返回它? – DaRoGa

回答

25

首先,你需要设置选项为您的HTTP请求 - 设置responseTypeResponseContentType.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' }) 
     } 
} 

然后,为了得到该文件,你需要subscribe到它,你可以创建新ObjectURL和使用window.open()在新标签页中打开PDF:

this.myService.downloadPDF().subscribe(
     (res) => { 
     var fileURL = URL.createObjectURL(res); 
     window.open(fileURL); 
     } 
    ); 
+0

嗨,Stefan.It显示我未能加载PDF文档。请帮助我。我正在使用Angular4。 – Mohit

+0

我可以下载,但无法在新的浏览器选项卡中显示。 – user1892203

3

角v.5.2.1答案:

downloadPDF(): any { 
    return this._httpClient.get(url, { responseType: 'blob'}) 
      .map(res => { 
      return new Blob([res], { type: 'application/pdf', }); 
     }); 
    } 

然后在*.component.ts

downloadPDF() { 
    let tab = window.open(); 
    this._getPdfService 
     .downloadPDF() 
     .subscribe(data => { 
     const fileUrl = URL.createObjectURL(data); 
     tab.location.href = fileUrl; 
     }); 
    } 

其重要的启动和打开一个新标签调用服务之前。然后将这个标签url设置为fileurl。

+0

为什么在调用服务之前打开选项卡很重要,而不是使用objecturl作为参数打开它(如所选答案中所示)? –

+1

@PauFracés因为您没有“允许”以“编程方式”打开选项卡,只允许用户打开选项卡,因此您必须启动一个尽可能接近用户交互的新选项卡,当用户点击然后调用'downloadPDF()'按钮。订阅内部距离用户交互太远。 – jonas