我们在浏览器(实际上是Chrome)中显示从REST后端API接收到的二进制图像时遇到问题。像这样在Java中定义的后端REST端点
@GetMapping(path = "/images/{imageId:\\d+}/data",produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody byte[] getImageData(@PathVariable long imageId) {
return ... skipped ...
}
在前端,我们执行以下步骤:
- 通过
fetch
JS方法调用请求图像数据
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编码的数据
https://www.dropbox.com/s/uvx042j2dgizkr9/base64.txt?dl=0
- 我们试图将base64编码的数据放入
<img>
元素中,但没有成功:(
所以问题是如何在前端为浏览器显示正确的base64图像?我们做错了什么?