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.

1
import { buildClient } from "@datocms/cma-client-node";
2
3
async function run() {
4
// Make sure the API token has access to the CMA, and is stored securely
5
const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
6
7
// Create upload resource from a local file
8
const upload2 = await client.uploads.createFromLocalFile({
9
// local path of the file to upload
10
localPath: "./image.png",
11
// if you want, you can specify a different base name for the uploaded file
12
filename: "different-image-name.png",
13
// skip the upload and return an existing resource if it's already present in the Media Area:
14
skipCreationIfAlreadyExists: true,
15
// specify some additional metadata to the upload resource
16
author: "New author!",
17
copyright: "New copyright",
18
default_field_metadata: {
19
en: {
20
alt: "New default alt",
21
title: "New default title",
22
focal_point: {
23
x: 0.3,
24
y: 0.6,
25
},
26
custom_data: {
27
watermark: true,
28
},
29
},
30
},
31
});
32
33
console.log(upload2);
34
}
35
36
run();
1
const result = {
2
id: '4124',
3
size: 444,
4
width: 30,
5
height: 30,
6
path: '/45/1496845848-different-image-name.png',
7
basename: 'image',
8
url: 'https://www.datocms-assets.com/45/1496845848-different-image-name.png',
9
format: 'jpg',
10
author: 'New author!',
11
copyright: 'New copyright',
12
notes: null,
13
default_field_metadata: {
14
en: {
15
alt: 'new default alt',
16
title: 'new default title',
17
focal_point: {
18
x: 0.3,
19
y: 0.6,
20
},
21
custom_data: {
22
watermark: true,
23
},
24
},
25
},
26
is_image: true,
27
tags: [],
28
};

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

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

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!

1
import { buildClient } from "@datocms/cma-client-browser";
2
3
// Make sure the API token has access to the CMA, and is stored securely
4
const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
5
6
function createUpload(file) {
7
return client.uploads.createFromFileOrBlob({
8
// File object to upload
9
fileOrBlob: file,
10
// if you want, you can specify a different base name for the uploaded file
11
filename: "different-image-name.png",
12
// skip the upload and return an existing resource if it's already present in the Media Area:
13
skipCreationIfAlreadyExists: true,
14
// specify some additional metadata to the upload resource
15
author: "New author!",
16
copyright: "New copyright",
17
default_field_metadata: {
18
en: {
19
alt: "New default alt",
20
title: "New default title",
21
focal_point: {
22
x: 0.3,
23
y: 0.6,
24
},
25
custom_data: {
26
watermark: true,
27
},
28
},
29
},
30
});
31
}
32
33
const fileInput = document.querySelector('input[type="file"]');
34
35
fileInput.addEventListener("change", async (event) => {
36
const files = event.target.files;
37
for (let file of files) {
38
createUpload(file).then((upload) => console.log(upload));
39
}
40
});
1
const response = {
2
id: '4124',
3
size: 444,
4
width: 30,
5
height: 30,
6
path: '/45/1496845848-different-image-name.png',
7
basename: 'image',
8
url: 'https://www.datocms-assets.com/45/1496845848-different-image-name.png',
9
format: 'jpg',
10
author: 'New author!',
11
copyright: 'New copyright',
12
notes: null,
13
default_field_metadata: {
14
en: {
15
alt: 'new default alt',
16
title: 'new default title',
17
focal_point: {
18
x: 0.3,
19
y: 0.6,
20
},
21
custom_data: {
22
watermark: true,
23
},
24
},
25
},
26
is_image: true,
27
tags: [],
28
};

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.

1
import { buildClient } from "@datocms/cma-client-node";
2
3
async function run() {
4
// Make sure the API token has access to the CMA, and is stored securely
5
const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
6
7
await client.uploads.createFromUrl({
8
url: "https://example.com/image.png",
9
onProgress: (info) => {
10
// info.type can be one of the following:
11
//
12
// * DOWNLOADING_FILE: client is downloading the asset from the specified URL
13
// * REQUESTING_UPLOAD_URL: client is requesting permission to upload the asset to the DatoCMS CDN
14
// * UPLOADING_FILE: client is uploading the asset
15
// * CREATING_UPLOAD_OBJECT: client is finalizing the creation of the upload resource
16
//
17
// Payload information depends on the type of notification
18
19
console.log(info.type, info.payload);
20
},
21
});
22
}
23
24
run();
1
DOWNLOADING_FILE { url: "https://example.com/image.png", progress: 20 }
2
DOWNLOADING_FILE { url: "https://example.com/image.png", progress: 90 }
3
DOWNLOADING_FILE { url: "https://example.com/image.png", progress: 100 }
4
5
REQUESTING_UPLOAD_URL { filaname: 'image.png' }
6
7
UPLOADING_FILE { progress: 10 }
8
UPLOADING_FILE { progress: 80 }
9
UPLOADING_FILE { progress: 100 }
10
11
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):

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

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