我们在浏览器(实际上是 Chrome)中显示从 REST 后端 API 接收的二进制图像时遇到问题.像这样在 Java 中定义的后端 REST 端点
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:
fetch
JS方法调用请求图片数据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();
});
}
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
<img>
元素但没有成功:(<img>
element without any success :(所以问题是如何在前端接收正确的 base64 图像以供浏览器显示?我们做错了什么?
So the question is how to receive on frontend correct base64 images for browser showing? What we do wrong?
这里有一些工作代码,基于这个例子以及上面的@somethinghere 评论.注意getImage
中response
是如何处理的:
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()
也就是说,一个更简单的选择是插入像 <img src=/images/id/data>
这样的标签,然后将所有加载/显示留给浏览器.在这种情况下,您的后端必须提供正确的内容类型.
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.
这篇关于如何在 JS 中对二进制图像进行 base64 编码以供浏览器显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!