服务器端相当于:
let result = await fetch("http://someurl");
result = await result.blob();
console.log(result)
const img = URL.createObjectURL(result);
is
let result = await fetch("http://someurl");
result = await result.arrayBuffer();
console.log(result)
const img = Buffer.from(result).toString("base64"));
然后图像在客户端呈现类似于:
<img src="data:image/png;base64, <%= img %>">
对于本例,使用 EJS;这里的重点是将图像数据转换为 Base-64 编码文本,然后可以使用图像数据 URI 进行渲染(https://css-tricks.com/data-uris/)
请注意,只有当获取图像数据需要某种服务器端身份验证时才需要这种跳环,就像在大多数情况下您只需这样做:
<img src="http://someurl">
我有以下(精简)代码,其中图像只有在经过身份验证后才能访问:
export function getImage({ imageUrl, token }) {
return fetch(`${apiServer}/${imageUrl}`, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((response) => response.arrayBuffer())
.then((blob) => Buffer.from(blob).toString("base64"));
}