Importing media from a URL

How to import media from a URL when using the Drag and Drop capability.

Apps can combine the Content and Drag and Drop capabilities to import media from a URL at the end of a drag event. There are two reasons you might want to do this:

  • When working with images, it's faster and more efficient than using data URLs
  • When working with videos, it's a requirement due to their file size

This guide explains how to use the capabilities together.

Prerequisites

Step 1: Initialize the capabilities

  1. Import the getContent and getDragAndDrop functions:

    import { getContent } from "@canva/content";
    import { getDragAndDrop } from "@canva/drag-drop"
  2. Call the functions to initialize the capabilities:

    const content = getContent();
    const dragAndDrop = getDragAndDrop();

Step 2: Make a node draggable

Call the makeDraggable method as you usually would, but pass through a function that will be called at the end of a drag event. The name of this function depends on the type of media being created:

  • Images
  • Videos

When adding an image to a design, the function must be called resolveImageRef:

resolveImageRef: async () => {
const upload = await content.queueMediaUpload({
type: "VIDEO",
mimeType: "video/mp4",
id: "video",
url: "https://www.canva.dev/example-assets/video-import/video.mp4",
thumbnailImageUrl: "https://www.canva.dev/example-assets/video-import/thumbnail-image.jpg",
thumbnailVideoUrl: "https://www.canva.dev/example-assets/video-import/thumbnail-video.mp4",
});
if (upload.type !== "done") {
throw new Error("Something went wrong!");
}
return upload;
},

Step 3: Resolve a media reference

In the provided function:

  1. Call the queueMediaUpload method.
  2. Throw an error if something goes wrong.
  3. Return the result of the queued upload.

Once again, the exact properties depend on the type of media being added to a design:

  • Images
  • Videos

The following snippet demonstrates how to resolve a media reference for an image:

resolveImageRef: async () => {
const upload = await content.queueMediaUpload({
type: "IMAGE",
id: "8f43953d9f0517df981dc113b8a7640c",
mimeType: "image/svg+xml",
url: "https://www.canva.dev/example-assets/image-import/image.jpg",
thumbnailUrl:
"https://www.canva.dev/example-assets/image-import/thumbnail.jpg",
width: 160,
height: 22,
});
if (upload.type !== "done") {
throw new Error(`Something went wrong!`);
}
return upload;
};