NodeJS 创建对象URL错误:'参数必须是Blob的示例,已收到Blob的示例'

wtlkbnrh  于 2023-01-30  发布在  Node.js
关注(0)|答案(2)|浏览(272)

我有一条包含以下内容的快速路线:

let result = await fetch("http://someurl");
result = await result.blob();
console.log(result)
const img = URL.createObjectURL(result);

这将产生以下错误(在第4行):
TypeError: The "obj" argument must be an instance of Blob. Received an instance of Blob
这是怎么回事?
如果有用,console.log的结果是:

Blob {
  [Symbol(type)]: 'image/png',
  [Symbol(buffer)]: <Buffer 89 50 4e  ... 481501 more bytes>
}

获取路由转到另一个调用res.sendFile(myfilepath)的Express应用程序

vuktfyat

vuktfyat1#

正如您在评论中提到的,当URL.createObjectURL在服务器上使用时会发生这种情况,通常是由使用服务器端渲染的应用程序使用。
在调用URL.createObjectURL之前,您可以执行document检查以确保您处于浏览器中,如下所示:

let result, img

if (typeof document !== 'undefined') {
  result = await fetch("http://someurl");
  result = await result.blob();
  console.log(result)
  img = URL.createObjectURL(result);
}
zi8p0yeb

zi8p0yeb2#

服务器端等效于:

let result = await fetch("http://someurl");
result = await result.blob();
console.log(result)
const img = URL.createObjectURL(result);

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"));
}

相关问题