Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Assets

In some cases, uploading assets using the UI is impractical. Say you want to upload a ton of images. If so, you'll want to use the assets API directly.

Protip

To delete an asset, you must delete the associated Sanity document.

POST assets/images/:dataset

To upload an image, do a POST request to

myProjectId.api.sanity.io/v2021-06-07/assets/images/myDataset

with your file in the request body. E.g.:

curl \
  -X POST \
  -H 'Content-Type: image/jpeg' \
  --data-binary "@/Users/mike/images/bicycle.jpg" \
  'https://myProjectId.api.sanity.io/v2021-03-25/assets/images/myDataset'

Input

import sanityClient from '@sanity/client'
import {basename} from 'path'
import {createReadStream} from 'fs'

const client = sanityClient({
  projectId: 'myProjectId',
  dataset: 'myDatasetName',
  token: 'myToken'
})

const filePath = '/Users/mike/images/bicycle.jpg'
client.assets.upload('image', createReadStream(filePath), {
  filename: basename(filePath)
}).then(imageAsset => {
  console.log('got imageAsset', imageAsset)
})

Output

{
  "_id": "image-abc123_0G0Pkg3JLakKCLrF1podAdE9-538x538-jpg",
  "_type": "sanity.imageAsset", // type is prefixed by sanity schema
  "assetId": "0G0Pkg3JLakKCLrF1podAdE9",
  "path": "images/myproject/mydataset/abc123_0G0Pkg3JLakKCLrF1podAdE9-538x538.jpg",
  "url": "https://cdn.sanity.io/images/myproject/mydataset/abc123_0G0Pkg3JLakKCLrF1podAdE9-538x538.jpg",
  "originalFilename": "bicycle.jpg",
  "size": 2097152, // File size, in bytes
  "metadata": {
    "dimensions": {
      "height": 538,
      "width": 538,
      "aspectRatio": 1.0
    },
    "location":{ // only present if the original image contained location metadata
      "lat": 59.9241370,
      "lon": 10.7583846,
      "alt": 21.0
    }
  }
}

Was this article helpful?