2017-03-07 97 views
2

我正在嘗試使用.Net核心web api使用angular 2下載PDF(以及word,excel和image)文件。我在這裏粘貼了一些代碼示例,下載該文件,但是當我嘗試打開下載的文件時,它會給我帶來損壞的文件。使用angular 2和.net核心webapi下載PDF文件

這裏是我的.NET的核心Web API代碼

public HttpResponseMessage GetTestPdfFile() 
     { 
      var response = new HttpResponseMessage(HttpStatusCode.OK); 
      response.Content = new ByteArrayContent(myArray); //byte[] myArray is byte[] of file downloaded from Azure blob 
      //response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("inline"); 
      response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); 
      response.Content.Headers.ContentDisposition.FileName = myFileName; 
      response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf"); 
      return response; 
     } 

我也曾嘗試另一個代碼示例

public FileResult TestDownload(int id) 
     { 
      HttpContext.Response.ContentType = "application/pdf"; 
      FileContentResult result = new FileContentResult(myArray, "application/pdf") 
      { 
       FileDownloadName = "test.pdf" 
      }; 

      return result; 
     } 

這是我在角服務

getTestPdfFile(): Observable<any> { 
     let url = 'API_URL' 
     let headers1 = new Headers(); 
     headers1.append('Content-Type', 'application/pdf'); 
     headers1.append('responseType', 'arrayBuffer'); 

     return this.http.get(url, {headers: headers1}) 
      .map(res => { 
       var contentType = 'application/pdf'; 
       var blob = new Blob([res.arrayBuffer()], { type: contentType }); 
       return blob; 
      }) 
    } 

這我是如何訂閱迷戀的

this.myService.getTestPdfFile() 
     .subscribe(blob => { 
       var link=document.createElement('a'); 
       link.href=window.URL.createObjectURL(blob); 
       link.download="Test.pdf"; 
       link.click(); 
      }, error => {}); 
    } 

回答

2

我從來沒有運氣使用observables下載物品。我所做的是使用window.open("http://urlToDocument.Test.pdf", "_blank")。這將下載或提示在新標籤中下載文件。

+0

感謝。我發現了答案。 – Jay

2

我不得不改變我的角度服務於下方,所有工作得很好

getTestPdfFile(): Observable<any> { 
     let url = 'API_URL' 
     return this.http.get(url, { responseType: ResponseContentType.Blob }) 
         .map(res => res.blob()) 
         .catch(this.handleError) 
    } 

我用這作爲我的web API

public FileResult TestDownload(int id) 
     { 
      HttpContext.Response.ContentType = "application/pdf"; 
      FileContentResult result = new FileContentResult(myArray, "application/pdf") 
      { 
       FileDownloadName = "test.pdf" 
      }; 

      return result; 
     } 
+0

謝謝,那就是訣竅。 – SHM