在 Circuit JS SDK 中通过 URL 在附件中发送图像

Send image in attachments by URL in Circuit JS SDK

我正在使用 Circuit JS SDK 并希望发送带有图片的消息。我在文档中发现我应该将 item.attachments 设置为 File[] 对象。但是如果我只有图像URL(比如https://abc.cde/fgh.png)怎么办?

为了能够 post 对话中的图像,图像需要上传到 Circuit,正如您已经发现的那样,这是在 addTextItem API 内部完成的。是的,这个 API 需要一个 File 对象数组。

您需要通过 XMLHttpRequest 将图像下载为 blob,然后构造一个 File 对象。

  const xhr = new XMLHttpRequest();
  xhr.responseType = 'blob';
  xhr.open('GET',<url of image> , true);

  xhr.onreadystatechange = async () => {
    if (xhr.readyState == xhr.DONE) {
      const file = new File([xhr.response], 'image.jpg', { lastModified: Date.now() });
      const item = await client.addTextItem(convId.value, { 
        attachments: [file]
      });
    }
  };

  xhr.send();

这是一个jsbin https://output.jsbin.com/sumarub