2016-11-28 35 views
0

%PDF-1.7% 0 OBJ <> 流 XZ PDF响应[oFiF8HBR @ TJZ!/ R \ n d Jy/ w V x w w ; _ # S !U: t| H 9c $ @,y 18 ' q wr8N [email protected] Y8) I x4 ) fG_ {2“ 䔼 qB ŸtSEg/如何读取角2.0

我正在从API中得到这样的响应,我试着在调用函数,但得到以下错误:

error = SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse() at Function.Json.parse

我的代码是:

downloadInvoice(invoicePdfUrl){ 
    let invoiceId = invoicePdfUrl.split('/')[2]; 
    try{ 
     this.invoiceSub = this.billingService.downloadInvoicePdf(invoiceId).subscribe(
     response => { 
      this.downloadFile(response),//console.log(data), 
      error => console.log("Error downloading the file."), 
      () => console.info("OK"); 
     }, 
     error => { 
      console.log(error); 
     } 
    ); 
    }catch(err){ 
     this.errorMsg = 'Something went wrong. Try again later.'; 
     throw err; 
    } 


downloadFile(data: Response){ 
    var blob = new Blob([data], { type: 'text/csv' }); 
    var url= window.URL.createObjectURL(blob); 
    window.open(url); 
    } 

在服务:

downloadInvoicePdf(invoiceId){ 
    let apiUrl = getApiUrl("GET_INVOICE_PDF", [API_PATH.API_VERSION2, invoiceId]); //this method return me the exact url to be hit based on the params 
    let headers = new Headers({ 'Accept': 'application/pdf'}); 
    let options = new RequestOptions({ 
     headers : headers 
    }); 

    return this.http.get(API_PATH.BASE_ACCOUNTS_ENDPOINT + apiUrl,options).map(res => res.json(); 
    // return 
    } 

请指引我通过这样的反应的处理。

+0

您想要做什么响应?在客户端浏览器下载它?在一个框架中显示它?将它发回服务器? –

+0

在客户端浏览器中下载 – monica

回答

2

首先:您错过了.map(res => res.json()>>>)<<<;的右括号 - 也许这只是一个复制/粘贴问题。

但是现在回到您的实际问题:您收到PDF作为回复,并尝试使用JSON解析器解析该PDF回应 - >这无法正常工作,这就像有一个中文文本,希望没有人知道什么汉字要理解那些文字。

根据您的使用情况,您需要:

  1. 一个PDF解析器,如果你想提取数据
  2. 一个PDF-渲染如果你想显示PDF(例如:https://mozilla.github.io/pdf.js/
  3. A 文件下载程序如果您要将该文件下载到用户本地系统(例如:https://github.com/eligrey/FileSaver.js/) (虽然有更好的方法来做到这一点比角度HTTP客户端)

=>对于一个简单的文件下载,因为你正在做一个GET-请求,如果您只是生成下载网址并将其绑定到模板中的锚标记,它会是最简单的:

<a [attr.href]="pdfDownloadLink">Download me!</a>