0

i have a spring boot backend ... made a service that returns a byte array image .. how to receive it in Angular and render it...

here's my angular code :

getFile(id) {
const _loadFileByIdUrl = environment.baseUrl + `finance/api/getFile`;
const fd = new FormData();
fd.append('id', id);
return this.http.post<any>(_loadFileByIdUrl, fd
 );
} 

i'm trying to console.log() the resoponse is 200 but i got error message : message: "Http failure during parsing for http://localhost:8080/finance/api/getFile"

Helix
  • 11
  • 9

1 Answers1

1

Unless you indicate that a different response type is expected, the http client attempts to parse the response as JSON. Use the responseType blob for binary data:

this.http.post(_loadFileByIdUrl, fd, { responseType: 'blob' });

Given that you have an image tag in your template, such as:

<img #smartesImage />

You could then access the image in your template like so

@ViewChild('smartesImage') smartesImage: ElementRef<any>;

And actually display the binary data using the following code:

this.http.post(_loadFileByIdUrl, fd, { responseType: 'blob'}).subscribe(res => {
   const objectURL = URL.createObjectURL(res);
   this.smartesImage.nativeElement.src = objectURL;
});
Jan Wendland
  • 1,350
  • 9
  • 17
  • when putting this line : this.http.post(_loadFileByIdUrl, fd, { responseType: 'blob' }); i get this error : Type '"blob"' is not assignable to type '"json" – Helix Mar 09 '19 at 19:10