如何以角度2

时间:2017-08-22 11:01:44

标签: angular2-services

这是在下载Pdf文件时以角度2下载pdf文件的功能它是损坏的文件。那么我该如何解决这个问题呢。 它显示这样的损坏数据。 %PDF-1.5 % ↵660obj <> endobj

downloadFile() {
    //this.http.get('https://contactsapi.apispark.net/v1/companies/').subscribe(
    this.http.get('assets/Files/booking.pdf').subscribe(
      (response: any) => {
        console.log(response);
        let parsedResponse =(response)
        var blob = new Blob([response], {type: 'application/pdf'});
        var filename = 'booking.pdf';
        saveAs(blob, filename);
      });
  }

3 个答案:

答案 0 :(得分:4)

我们需要这个软件包文件保护程序,您安装如“npm install file-saver --save”,然后您可以尝试这样

 public downloadCSVFile(){
    this.downloadPdf().subscribe(
        (res) => {      
            saveAs(res,'test.pdf')
        }
    );


}

public downloadPdf(): any {
    let url='your url'
    let headers = new Headers();
    headers.append('Authorization', 'JWT ' + localStorage.getItem('id_token'));
    return this.http.get(url,{  headers: headers,responseType: ResponseContentType.Blob }).map(
        (res) => {
            return new Blob([res.blob()], { type: 'application/pdf' })
        })
}

答案 1 :(得分:1)

角度6

downloadPdfFile.service.ts

import {
  HttpClient,
  HttpHeaders
} from '@angular/common/http';

import { map } from 'rxjs/operators';

     downloadPDF(dataObj)
        {

          let headerOptions = new HttpHeaders({
          'Content-Type': 'application/json', 
          'Accept': 'application/pdf'
         //   'Accept': 'application/octet-stream', // for excel file
        }); 

            let requestOptions = {headers : headerOptions,responseType: 'blob' as 'blob'}; 
            // post or get depending on your requirement
              this.http.post(serviceURL,dataObj,requestOptions).pipe(map((data :any)  => {

                let blob = new Blob([data], { 
                   type: 'application/pdf' // must match the Accept type
                // type: 'application/octet-stream' // for excel 
                });
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = 'samplePDFFile.pdf';
                link.click();
                window.URL.revokeObjectURL(link.href);

              })).subscribe((result : any) => {
              });

        }

在组件文件中只需调用方法

downloadPdf()
{
     let dataObj={}
     this.downoloadPdfFileService.downloadPDF(dataObj);

}

答案 2 :(得分:0)

如果您想要一个简单的解决方案,请尝试以下操作:

<a download="b82d8486-a931-421c-b594-f4d3129746e5.pdf" target="_blank" href="/assets/files/b82d8486-a931-421c-b594-f4d3129746e5.pdf">
                Download pdf
              </a>