问题描述
我们在浏览器(实际上是 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方法调用请求图片数据
- 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();
});
}
- 因此在前端我们有这种格式的原始二进制图像数据(到目前为止一切都很好 - 它实际上是 JPEG 二进制数据).附上源JPEG
https://www.dropbox.com/s/8mh6xz881by5lu1/0gCrmsLkgik.jpg?dl=0
- 然后我们调用这段代码来接收base64编码的图片
let reader = new FileReader();
reader.addEventListener('loadend', event => {
console.log(event.srcElement.result)
});
reader.readAsDataURL(new Blob([data]));
- 因此我们有 一些东西看起来像 base64 编码的数据
- as a result we have something looks like base64 encoded data
https://www.dropbox.com/s/uvx042j2dgizkr9/base64.txt?dl=0
- 我们尝试将 base64 编码数据放入
<img>
元素但没有成功:(
- we tried to put base64 encoded data into
<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 编码以供浏览器显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!