circuit-sdk

Send image in attachments by URL in Circuit JS SDK


I'm using a Circuit JS SDK and want to send message with attached image. I found on documentation that I should set the item.attachments to File[] object. But how can I do it if I have only image URL (like https://abc.cde/fgh.png)?


Solution

  • To be able to post an image in a conversation, the image needs to be uploaded to Circuit which is done internally in the addTextItem API as you already found out. And yes this API takes an array of File objects.

    You will need to download the image via XMLHttpRequest as blob and then construct a File object.

      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();
    

    Here is a jsbin https://output.jsbin.com/sumarub