👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

File uploads - Allow users of my app to upload assets (PDF or images) through a file picker.

8 replies
Last updated: Aug 11, 2021
I never knew how difficult file uploads could be. My goal is to allow users of my app to upload assets (PDF or images) through a file picker. I want to upload the file to sanity, return the file URL and name in the response, and save the file name and URL into my database so that they can be downloaded or deleted in the future. Is there a tutorial to follow? I’ve read https://www.sanity.io/docs/http-api-assets over and over again, but I do not see a use case where it would work because of the following line of code:
const filePath = '/Users/mike/images/bicycle.jpg'
File path is not available with a file picker. Any direction or ideas would be great.
Jul 27, 2021, 5:45 AM
Hey
user U
, as a workaround/temp solution you can upload your asset to a 3rd party service like Firebase, get back a URL then upload that to Sanity.io
Jul 27, 2021, 5:49 AM
Is that what you ended up doing?
Jul 27, 2021, 5:53 AM
Jul 27, 2021, 5:58 AM
Thanks for linking those examples. The flow makes sense, but it sucks having to learn Firebase just to do this.
Jul 27, 2021, 6:06 AM
I assume that you’re doing this outside of the studio,
@sanity/client
works in the browser so you can do something like this:

const file = document.querySelector('input[type="file"]').files[0]

const res = await client.assets.upload('file', file, {
  filename: file.name
})

const { url, assetId } = res
// write the url somewhere else...
File picker return a File object which is a fancy blob so you should be able to pass it straight to the client
Jul 27, 2021, 7:20 AM
I’ll try this tomorrow. Thank you!
Jul 27, 2021, 7:22 AM
Worked like a charm. Thank you.
Jul 28, 2021, 1:50 AM
user G
How are you handling not sharing your token from the frontend? If I were to use a lambda function (netlify), I am limited to a 10 seconds, which may not allow file uploads on slower connections. It seems this is solved with uploading to an S3 bucket with a signed URL. I don’t think sanity does this.
Aug 11, 2021, 8:07 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?