Search code examples
sanity

How to download file from Sanity via HTTP?


I would like to know if there is possibility to download file from Sanity with HTTP request?

I only have reference ID:

{
   file: {
      asset: {
       _ref: "file-fxxxxxxxxxxxxxxxxxxxx-xlsx"
       _type: "reference"
       }    
    }
}

I would like to do this is this scenario:

<a href="https://cdn.sanity.io/assets/clientID/dataset/file-xxxxxxxxxxx-xlsx"> 
Download File 
</a>

Solution

  • You can, indeed 🎉 With a bit of custom code you can do it just from the _ref, which is the file document's _id

    Creating the URL from the _ref/_id of the file

    The _ref/_id structure is something like this: file-{ID}-{EXTENSION} (example: file-207fd9951e759130053d37cf0a558ffe84ddd1c9-mp3).

    With this, you can generate the downloadable URL, which has the following structure: https://cdn.sanity.io/files/{PROJECT_ID}/{DATASET}/{ID_OF_FILE}.{EXTENSION}. Here's some pseudo Javascript code for the operation:

    const getUrlFromId = ref => {
      // Example ref: file-207fd9951e759130053d37cf0a558ffe84ddd1c9-mp3
      // We don't need the first part, unless we're using the same function for files and images
      const [_file, id, extension] = ref.split('-');
      return `https://cdn.sanity.io/files/${PROJECT_ID}/${DATASET}/${id}.${extension}`
    }
    

    Querying the URL directly

    However, if you can query for the file's document with GROQ that'd be easier:

    *[(YOUR FILTER HERE)] {
      file->{ url } // gets the URL from the referenced file
    }
    

    You can do the same with images, too.