Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot, angular 7 Unexpected token % in JSON at position 0 at JSON.parse when download a pdf

Here is my backend :

public ResponseEntity getTestByURL(String filename) throws IOException {

    File myExport = new File(location + filename);

    HttpHeaders header = new HttpHeaders();
    header.add("Content-disposition", "attachment; filename=" + filename);

    String absolutePath = myExport.getAbsolutePath();
    InputStreamResource resource = new InputStreamResource(new FileInputStream(absolutePath));

    return ResponseEntity.ok()
            .headers(header)
            .contentLength(myExport.length())
            .contentType(MediaType.parseMediaType("application/pdf"))
            .body(resource);
}

@RequestMapping(value = "/url/{url}", produces = MediaType.APPLICATION_PDF_VALUE, method = GET)
public ResponseEntity<InputStreamResource> getTestByURL(@PathVariable(value = "url") String url) throws IOException {
    return testService.getTestByURL(url);
}

And frontend :

getPDF(url: string): Observable<HttpResponse<Blob>> {
    return this.http.get<HttpResponse<Blob>>(`${this.urlPDF}` + '/' + url, {
        headers: new HttpHeaders({
        'Content-Type':  'application/pdf',
        responseType : 'blob',
        Accept : 'application/pdf',
        observe : 'response'
        })
    });
}

Give me an error, HttpErrorResponse status: 200. "Http faillure during parsing ..." "Unexpected token % in JSON at position 0 at JSON.parse"

like image 749
Florian Gojon Avatar asked Oct 24 '25 02:10

Florian Gojon


1 Answers

You are calling service without responseType params apart from HttpHeaders. HttpClient by default take this value as json. You will have to specify it.

https://angular.io/api/common/http/HttpRequest

see constructor signature:- constructor(method: string, url: string, third?: T | { headers?: HttpHeaders responseType?: "arraybuffer" | "blob" | "text" | "json"............ })

working code:-

let  headers= new HttpHeaders({
    'Content-Type':  'application/pdf',
    responseType : 'blob',
    Accept : 'application/pdf',
    observe : 'response'
    })
  return this.httpClient.get(this.resourcePrefix+ '/test', {
    headers:headers , responseType: 'blob' 
});  

For download you can google it. or I usually use this to download

this.httpService.test().subscribe(res =>{
  console.log(res);
  const file = res;
    const url = window.URL.createObjectURL(new Blob([res as BlobPart], { type: 'application/pdf' }));

    var link = document.createElement('a');
    document.body.appendChild(link);
    link.setAttribute('style', 'display: none');
    link.href = url;
    link.download = 'test.pdf';
    link.click();
});
like image 57
Himanshu Sharma Avatar answered Oct 26 '25 17:10

Himanshu Sharma