2017-03-07 14 views
2

.Net Core Web APIを使用してAngular 2を使用してPDF(およびそれ以降の単語、Excelおよび画像)ファイルをダウンロードしようとしています。私はファイルをダウンロードするいくつかのコードサンプルをここに貼り付けましたが、ダウンロードしたファイルを開こうとすると、破損したファイルが作成されます。ここで Anger 2と.Net core webapiを使用してPDFファイルをダウンロード

は、これは私が角度サービス

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; 
      }) 
    } 

これをして持っているものである

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

      return result; 
     } 

私はまた、別のコードサンプルを試してみました

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; 
     } 

私の.NETのコアウェブAPIコードです私がobsevableを購読している方法です

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

答えて

2

私は観覧料を使ってアイテムをダウンロードしたことがありませんでした。私が代わりにしたのはwindow.open("http://urlToDocument.Test.pdf", "_blank")です。これにより、新しいタブでファイルをダウンロードまたはダウンロードするよう指示されます。

+0

おかげでこれを使用しています

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

うまく働きました。投稿された回答が見つかりました。 – Jay

2

私は以下に私の角度サービスを変更しなければならなかったし、すべてが、私は自分の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

関連する問題