Sorry, no results found for "".

Show examples in:
Javascript HTTP

Content Management API > Upload

Create a new upload

The DatoCMS clients provide numerous methods for users to upload resources. The method you choose can be influenced by different aspects like the platform you're using (such as Node.js or a browser) and where the resource is coming from — like a local file, a remote URL, or a File or Blob obtained from <input type="file" /> elements.

This example shows how to add assets to the Media Area by uploading a local file.

import { buildClient } from "@datocms/cma-client-node";
async function run() {
// Make sure the API token has access to the CMA, and is stored securely
const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
// Create upload resource from a local file
const upload2 = await client.uploads.createFromLocalFile({
// local path of the file to upload
localPath: "./image.png",
// if you want, you can specify a different base name for the uploaded file
filename: "different-image-name.png",
// skip the upload and return an existing resource if it's already present in the Media Area:
skipCreationIfAlreadyExists: true,
// specify some additional metadata to the upload resource
author: "New author!",
copyright: "New copyright",
default_field_metadata: {
en: {
alt: "New default alt",
title: "New default title",
focal_point: {
x: 0.3,
y: 0.6,
},
custom_data: {
watermark: true,
},
},
},
});
console.log(upload2);
}
run();
const result = {
id: '4124',
size: 444,
width: 30,
height: 30,
path: '/45/1496845848-different-image-name.png',
basename: 'image',
url: 'https://www.datocms-assets.com/45/1496845848-different-image-name.png',
format: 'jpg',
author: 'New author!',
copyright: 'New copyright',
notes: null,
default_field_metadata: {
en: {
alt: 'new default alt',
title: 'new default title',
focal_point: {
x: 0.3,
y: 0.6,
},
custom_data: {
watermark: true,
},
},
},
is_image: true,
tags: [],
};

Here's a demonstration of how you can uploading an asset from a remote location, accessible through a URL.

import { buildClient } from "@datocms/cma-client-node";
async function run() {
// Make sure the API token has access to the CMA, and is stored securely
const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
// Create upload resource from a remote URL
const upload1 = await client.uploads.createFromUrl({
// remote URL to upload
url: "https://example.com/image.png",
// if you want, you can specify a different base name for the uploaded file
filename: "different-image-name.png",
// skip the upload and return an existing resource if it's already present in the Media Area:
skipCreationIfAlreadyExists: true,
// specify some additional metadata to the upload resource
author: "New author!",
copyright: "New copyright",
});
console.log(upload2);
}
run();
const result = {
id: '4124',
size: 444,
width: 30,
height: 30,
path: '/45/1496845848-different-image-name.png',
basename: 'image',
url: 'https://www.datocms-assets.com/45/1496845848-different-image-name.png',
format: 'jpg',
author: 'New author!',
copyright: 'New copyright',
notes: null,
default_field_metadata: {
en: {
alt: 'new default alt',
title: 'new default title',
focal_point: {
x: 0.3,
y: 0.6,
},
custom_data: {
watermark: true,
},
},
},
is_image: true,
tags: [],
};

This example shows how to add assets to the Media Area from the browser, starting from a File or Blob object.

Important! Make sure to use the @datocms/cma-client-browser package, or the client.uploads.createFromFileOrBlob() method won't be available!

import { buildClient } from "@datocms/cma-client-browser";
// Make sure the API token has access to the CMA, and is stored securely
const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
function createUpload(file) {
return client.uploads.createFromFileOrBlob({
// File object to upload
fileOrBlob: file,
// if you want, you can specify a different base name for the uploaded file
filename: "different-image-name.png",
// skip the upload and return an existing resource if it's already present in the Media Area:
skipCreationIfAlreadyExists: true,
// specify some additional metadata to the upload resource
author: "New author!",
copyright: "New copyright",
default_field_metadata: {
en: {
alt: "New default alt",
title: "New default title",
focal_point: {
x: 0.3,
y: 0.6,
},
custom_data: {
watermark: true,
},
},
},
});
}
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener("change", async (event) => {
const files = event.target.files;
for (let file of files) {
createUpload(file).then((upload) => console.log(upload));
}
});
const response = {
id: '4124',
size: 444,
width: 30,
height: 30,
path: '/45/1496845848-different-image-name.png',
basename: 'image',
url: 'https://www.datocms-assets.com/45/1496845848-different-image-name.png',
format: 'jpg',
author: 'New author!',
copyright: 'New copyright',
notes: null,
default_field_metadata: {
en: {
alt: 'new default alt',
title: 'new default title',
focal_point: {
x: 0.3,
y: 0.6,
},
custom_data: {
watermark: true,
},
},
},
is_image: true,
tags: [],
};

Regardless of the upload method, you can always get information about the operation's progress by listening to the events that hit the onProgress callback.

import { buildClient } from "@datocms/cma-client-node";
async function run() {
// Make sure the API token has access to the CMA, and is stored securely
const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
await client.uploads.createFromUrl({
url: "https://example.com/image.png",
onProgress: (info) => {
// info.type can be one of the following:
//
// * DOWNLOADING_FILE: client is downloading the asset from the specified URL
// * REQUESTING_UPLOAD_URL: client is requesting permission to upload the asset to the DatoCMS CDN
// * UPLOADING_FILE: client is uploading the asset
// * CREATING_UPLOAD_OBJECT: client is finalizing the creation of the upload resource
//
// Payload information depends on the type of notification
console.log(info.type, info.payload);
},
});
}
run();
DOWNLOADING_FILE { url: "https://example.com/image.png", progress: 20 }
DOWNLOADING_FILE { url: "https://example.com/image.png", progress: 90 }
DOWNLOADING_FILE { url: "https://example.com/image.png", progress: 100 }
REQUESTING_UPLOAD_URL { filaname: 'image.png' }
UPLOADING_FILE { progress: 10 }
UPLOADING_FILE { progress: 80 }
UPLOADING_FILE { progress: 100 }
CREATING_UPLOAD_OBJECT undefined

Each available method yields a cancellable promise, granting the ability to halt a currently running upload operation.

It is possible to cancel an upload operation by calling the .cancel() method on the promise returned by one of the upload creation methods (createFromUrl(), createFromLocalFile() in NodeJS, createFromFileOrBlob() in browser):

import { buildClient, CanceledPromiseError } from "@datocms/cma-client-browser";
// Make sure the API token has access to the CMA, and is stored securely
const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
let cancelablePromise = null;
document.querySelector("button").addEventListener("click", () => {
if (cancelablePromise) {
cancelablePromise.cancel();
}
});
document
.querySelector('input[type="file"]')
.addEventListener("change", async (event) => {
cancelablePromise = client.uploads.createFromFileOrBlob({
fileOrBlob: event.target.files[0],
});
cancelablePromise
.then((upload) => {
cancelablePromise = null;
console.log(upload);
})
.catch((e) => {
if (e instanceof CanceledPromiseError) {
console.log("User canceled the upload process!");
} else {
throw e;
}
});
});
{
id: "q0VNpiNQSkG6z0lif_O1zg",
size: 444,
width: 30,
height: 30,
path: "/45/1496845848-digital-cats.jpg",
basename: "digital-cats",
filename: "digital-cats.jpg",
url: "https://www.datocms-assets.com/45/1496845848-digital-cats.jpg",
format: "jpg",
author: "Mark Smith",
copyright: "2020 DatoCMS",
notes: "Nyan the cat",
md5: "873c296d0f2b7ee569f2d7ddaebc0d33",
duration: 62,
frame_rate: 30,
blurhash: "LEHV6nWB2yk8pyo0adR*.7kCMdnj",
thumbhash: "UhqCDQIkrHOfVG8wBa2v39z7CXeqZWFLdg==",
mux_playback_id: "a1B2c3D4e5F6g7H8i9",
mux_mp4_highest_res: "high",
default_field_metadata: {
en: {
title: "this is the default title",
alt: "this is the default alternate text",
custom_data: { foo: "bar" },
focal_point: { x: 0.5, y: 0.5 },
},
},
is_image: true,
created_at: "2020-04-21T07:57:11.124Z",
updated_at: "2020-04-21T07:57:11.124Z",
mime_type: "image/jpeg",
tags: ["cats"],
smart_tags: ["robot-cats"],
exif_info: {
iso: 10000,
model: "ILCE-7",
flash_mode: 16,
focal_length: 35,
exposure_time: 0.0166667,
},
colors: [
{ red: 206, green: 203, blue: 167, alpha: 255 },
{ red: 158, green: 163, blue: 93, alpha: 255 },
],
creator: { type: "account", id: "312" },
upload_collection: {
type: "upload_collection",
id: "uinr2zfqQLeCo_1O0-ao-Q",
},
}

Body parameters

id string Optional

RFC 4122 UUID of upload expressed in URL-safe base64 format

Example: "q0VNpiNQSkG6z0lif_O1zg"
path string Required

Upload path

Example: "/45/1496845848-digital-cats.jpg"
copyright string, null Optional

Copyright

Example: "2020 DatoCMS"
author string, null Optional

Author

Example: "Mark Smith"
notes string, null Optional

Notes

Example: "Nyan the cat"
default_field_metadata object Optional

For each of the project's locales, the default metadata to apply if nothing is specified at record's level.

Example: { en: { title: "this is the default title", alt: "this is the default alternate text", custom_data: { foo: "bar" }, focal_point: { x: 0.5, y: 0.5 }, }, }
tags Optional

Tags

Type: Array<string>
Example: ["cats"]
upload_collection Optional

Upload collection to which the asset belongs

Returns

Returns a resource object of type upload