To upload a new asset to a DatoCMS project you will need to perform three separate HTTP calls. This helps DatoCMS making the uploading process extremely fast, as we don't need to be a middleman between you (the user that wants to upload an asset) and the storage bucket.
We strongly recommend to use our Javascript client to upload new assets, as it provides helper methods that take care of all the details for you.
Upload path
Copyright
Author
Notes
For each of the project's locales, the default metadata to apply if nothing is specified at record's level.
Tags
The following examples are available:
This example shows how to add assets to the Media Area by uploading both local or remote files:
import { buildClient } from '@datocms/cma-client-node';function handleProgress(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 resourceconsole.log('Phase:', info.type);// Payload information depends on the type of notificationconsole.log('Details:', info.payload);}async function run() {const client = buildClient({ apiToken: '<YOUR_API_TOKEN>' });// Create upload resource from a remote URLconst upload1 = await client.uploads.createFromUrl({// remote URL to uploadurl: 'https://example.com/image.png',// if you want, you can specify a different base name for the uploaded filefilename: 'different-image-name.png',// skip the upload and return an existing resource if it's already present in the Media Area:skipCreationIfAlreadyExists: true,// be notified about the progress of the operation.onProgress: handleProgress,// specify some additional metadata to the upload resourceauthor: 'New author!',copyright: 'New copyright',});// Create upload resource from a local fileconst upload2 = await client.uploads.createFromLocalFile({// local path of the file to uploadlocalPath: './image.png',// if you want, you can specify a different base name for the uploaded filefilename: 'different-image-name.png',// skip the upload and return an existing resource if it's already present in the Media Area:skipCreationIfAlreadyExists: true,// be notified about the progress of the operation.onProgress: handleProgress,// specify some additional metadata to the upload resourceauthor: '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: [],};
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';const client = buildClient({ apiToken: '<YOUR_API_TOKEN>' });function createUpload(file) {return client.uploads.createFromFileOrBlob({// File object to uploadfileOrBlob: file,// if you want, you can specify a different base name for the uploaded filefilename: 'different-image-name.png',// skip the upload and return an existing resource if it's already present in the Media Area:skipCreationIfAlreadyExists: true,// be notified about the progress of the operation.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 resourceconsole.log('Phase:', info.type);// Payload information depends on the type of notificationconsole.log('Details:', info.payload);},// specify some additional metadata to the upload resourceauthor: '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: [],};
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';const client = buildClient({ apiToken: '<YOUR_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;}});});