6

I am new to angular and I have been struggling to figure out how to download a file, in my case a pdf file. This is the error I get:

Http failure during parsing for https://url...

In the debug console of the browser the is also an error:

SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse

Actually I am downloading a pdf file. Here is how my http call looks like:

  protected get<T>(url: string, params: any, defaultResult: T): Observable<T> {
    return this.httpClient.get<T>(url, {
    headers: myHeader,
    params: params
})
  .pipe(catchError(this.handleError(defaultResult))
  );

} How

edmond
  • 833
  • 3
  • 13
  • 31

3 Answers3

19

Since you are passing back a blob of data rather than JSON but not letting the httpclient know how to parse it back, angular is trying to parse response back as a JSON which is the default path.

Here is documentation from the angular website:

request(first: string | HttpRequest<any>, url?: string, options: {
    body?: any;
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe?: HttpObserve;
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
    withCredentials?: boolean;
} = {}): Observable<any>

responseType:

In addition to configuring request parameters such as the outgoing headers and/or the body, the options hash specifies two key pieces of information about the request: the responseType and what to observe. The responseType value determines how a successful response body will be parsed. If responseType is the default json, a type interface for the resulting object may be passed as a type parameter to request().

So in your case try:

    protected get<T>(url: string, params: any, defaultResult: T): Observable<any> {
        return this.httpClient.get(url, {
        headers: myHeader,
        params: params,
        responseType: 'blob'
    })
      .pipe(catchError(this.handleError(defaultResult))
      );

more info:

httpclient

documentation

Similar question Angular HttpClient "Http failure during parsing"

abann sunny
  • 928
  • 12
  • 15
0

In my case I just forgot to add the request options for the http client
before

public downloadSummaryByMat(mat:string){
    return this.http.get(this.url+'/reports/'+mat);
  }

after

public downloadSummaryByMat(mat:string){
    return this.http.get(this.url+'/reports/'+mat,{ responseType: 'arraybuffer' });
  }
-1

working for me thank you For component please check below

downloadFile(caseID) {
    console.log(caseID);
    this.mediaService.downloadFile(caseID).subscribe(
        (downloaded) => {
        console.log('File is Downloaded', downloaded);
        var url = window.URL.createObjectURL(downloaded);
        window.open(url);
    });
}