问题
We have a problem with showing in browser (actually Chrome) binary images receiving from REST backend API. The backend REST endpoint defined in Java like this
@GetMapping(path = "/images/{imageId:\\d+}/data", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody byte[] getImageData(@PathVariable long imageId) {
return ... skipped ...
}
On the frontend we do these steps:
- request image data via
fetch
JS method call
async function getImage(id) {
return await fetch(`${URL}/images/${id}/data`, {
method: 'GET',
headers: new Headers(HEADERS)
}).then(response => {
return response.text();
});
}
- thus on frontend we have raw binary image data in this format (so far so good - it's really JPEG binary data). Attached the source JPEG
https://www.dropbox.com/s/8mh6xz881by5lu1/0gCrmsLkgik.jpg?dl=0
- then we call this code to receive base64 encoded image
let reader = new FileReader();
reader.addEventListener('loadend', event => {
console.log(event.srcElement.result)
});
reader.readAsDataURL(new Blob([data]));
- as a result we have something looks like base64 encoded data
https://www.dropbox.com/s/uvx042j2dgizkr9/base64.txt?dl=0
- we tried to put base64 encoded data into
<img>
element without any success :(
So the question is how to receive on frontend correct base64 images for browser showing? What we do wrong?
回答1:
Here's some working code, based on this example and the @somethinghere's comment above. Pay attention to how the response
is handled in getImage
:
function getImage(id) {
return fetch(`https://placekitten.com/200/140`, {
method: 'GET',
}).then(response => {
return response.blob(); // <- important
});
}
async function loadAndDisplay() {
let blob = await getImage();
let imageUrl = URL.createObjectURL(blob);
let img = document.createElement('img');
img.src = imageUrl;
document.body.appendChild(img)
}
loadAndDisplay()
That said, a much simpler option would be just to insert a tag like <img src=/images/id/data>
and leave all loading/displaying to the browser. In this case your backend has to provide the correct content-type though.
来源:https://stackoverflow.com/questions/58730240/how-to-base64-encode-binary-image-in-js-for-browser-showing