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"
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With