我有这种情况,我使用 XMLHttpRequest 加载图像但没有将 responseType 设置为 blob。所以我收到一个字符串
我的问题是,在这种情况下还能渲染图像吗?
例如,我尝试将此字符串转换为 Blob
out = new Blob([imageString], { type: 'image/png' });
但这并没有呈现预期的图像。有什么建议吗?
这是我的节点后端如何将该图像发送到浏览器
app.get("/binary/*", (req: express.Request, res: express.Response) => {
const file = binaryPath + '/test.jpg';
res.sendFile(file);
});
终于明白了:如果你不想拥有
xhr.responseType = 'blob'
并且你想从接收到的数据创建一个url,那么你需要设置xhr.responseType = 'arraybuffer'
。这允许将二进制 xhr.response
转换为 blob,然后创建一个 URL.createObjectURL
.
重点是,当您不将
responseType
设置为二进制类型时,您将获得默认的xhr.responseType = 'text'
和utf8编码。然后 blob 创建失败。
我已将此解决方案包含在您的stackblitz中。
事实证明,当您未指定 responseType 时,数据被解码为 ASCII。因此,对于每个大于 127 的字符,您都会得到 253,因此图像会损坏。为避免这种情况,请添加
overrideMimeType
和 charset=x-user-defined
.
const client = new XMLHttpRequest();
client.overrideMimeType('image/jpeg; charset=x-user-defined');
client.open("GET", binaryPath + '/test.jpg', false);
client.send();
const blob = new Blob(
[Uint8Array.from(client.response, c => c.charCodeAt(0)).buffer],
{ type: "image/jpeg" });