[英]How to base64 encode binary image in JS for browser showing
We have a problem with showing in browser (actually Chrome) binary images receiving from REST backend API.我们在浏览器(实际上是 Chrome)中显示从 REST 后端 API 接收的二进制图像时遇到问题。 The backend REST endpoint defined in Java like this
在 Java 中定义的后端 REST 端点就像这样
@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:在前端,我们执行以下步骤:
fetch
JS method callfetch
JS 方法调用请求图像数据 async function getImage(id) {
return await fetch(`${URL}/images/${id}/data`, {
method: 'GET',
headers: new Headers(HEADERS)
}).then(response => {
return response.text();
});
}
https://www.dropbox.com/s/8mh6xz881by5lu1/0gCrmsLkgik.jpg?dl=0 https://www.dropbox.com/s/8mh6xz881by5lu1/0gCrmsLkgik.jpg?dl=0
let reader = new FileReader();
reader.addEventListener('loadend', event => {
console.log(event.srcElement.result)
});
reader.readAsDataURL(new Blob([data]));
https://www.dropbox.com/s/uvx042j2dgizkr9/base64.txt?dl=0 https://www.dropbox.com/s/uvx042j2dgizkr9/base64.txt?dl=0
<img>
element without any success:(<img>
元素中,但没有成功:( So the question is how to receive on frontend correct base64 images for browser showing?所以问题是如何在前端接收正确的 base64 图像以供浏览器显示? What we do wrong?
我们做错了什么?
Here's some working code, based on this example and the @somethinghere's comment above.这是一些工作代码,基于此示例和上面的@somethinghere 评论。 Pay attention to how the
response
is handled in getImage
:请注意在
getImage
中如何处理response
:
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.也就是说,一个更简单的选择是插入一个标签,如
<img src=/images/id/data>
并将所有加载/显示留给浏览器。 In this case your backend has to provide the correct content-type though.在这种情况下,您的后端必须提供正确的内容类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.