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"

2
  • Possible duplicate of BASE64 to image angular 2 Commented Mar 9, 2019 at 18:26
  • is base64 the best format to load an image from a server ? Commented Mar 9, 2019 at 18:30

1 Answer 1

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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

when putting this line : this.http.post<any>(_loadFileByIdUrl, fd, { responseType: 'blob' }); i get this error : Type '"blob"' is not assignable to type '"json"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.