2016-10-28 67 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