Skip to content

Support attachments in your app built with XMTP

Attachments smaller than 1MB can be sent using the AttachmentCodec. The codec will automatically encrypt the attachment and upload it to the XMTP network.

Install the package

npm i @xmtp/content-type-remote-attachment

In some SDKs, the AttachmentCodec is already included in the SDK. If not, you can install the package using the following command:

Import and register

JavaScript
import {
  ContentTypeAttachment,
  AttachmentCodec,
} from "@xmtp/content-type-remote-attachment";
// Create the XMTP client
const xmtp = await Client.create(signer, { env: "dev" });
xmtp.registerCodec(new AttachmentCodec());

Load local file

// Read local file and extract its details
const file = fs.readFileSync("xmtp.png");
const filename = path.basename("xmtp.png");
const extname = path.extname("xmtp.png");
console.log(`Filename: ${filename}`);
console.log(`File Type: ${extname}`);

Send encrypted file

// Convert the file to a Uint8Array
const blob = new Blob([file], { type: extname });
let imgArray = new Uint8Array(await blob.arrayBuffer());
 
const attachment = {
  filename: filename,
  mimeType: extname, //image, video or audio
  data: imgArray,
};
 
console.log("Attachment created", attachment);
await conversation.send(attachment, { contentType: ContentTypeAttachment });

Receive encrypted file

if (message.contentType.sameAs(ContentTypeAttachment)) {
  const blobdecoded = new Blob([message.content.data], {
    type: message.content.mimeType,
  });
  const url = URL.createObjectURL(blobdecoded);
}