A challenge I am facing is with my REST API where I have uploaded a PDF file. I am now trying to enable my Angular app to download the file when a user clicks on a button through the web browser. However, I am encountering an HttpErrorResponse with the error message:
"Unexpected token % in JSON at position 0"
After investigating, I found that the issue arises at position 0 due to a syntax error when parsing JSON data. Here is a snippet of my endpoint code:
@GetMapping("/help/pdf2")
public ResponseEntity<InputStreamResource> getPdf2(){
Resource resource = new ClassPathResource("/pdf-sample.pdf");
long r = 0;
InputStream is=null;
try {
is = resource.getInputStream();
r = resource.contentLength();
} catch (IOException e) {
e.printStackTrace();
}
return ResponseEntity.ok().contentLength(r)
.contentType(MediaType.parseMediaType("application/pdf"))
.body(new InputStreamResource(is));
}
This is how I am handling the service in my Angular app:
getPdf() {
this.authKey = localStorage.getItem('jwt_token');
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/pdf',
'Authorization' : this.authKey,
responseType : 'blob',
Accept : 'application/pdf',
observe : 'response'
})
};
return this.http
.get("http://localhost:9989/api/download/help/pdf2", httpOptions);
Finally, here is how I invoke the service to download the PDF file:
this.downloadService.getPdf()
.subscribe((resultBlob: Blob) => {
var downloadURL = URL.createObjectURL(resultBlob);
window.open(downloadURL);});