Uploading base64 images to Sanity and resolving a 400 error

16 replies
Last updated: Mar 28, 2022
I'm looking at the docs
client.assets.upload(type: 'file' | image', body: File | Blob | Buffer | NodeStream, options = {}): Promise<AssetDocument>
Can I upload base64 to to sanity? or no
Mar 28, 2022, 6:53 PM
I'm trying to upload base64 image to sanity
Mar 28, 2022, 7:22 PM
const handleOnSave = async(imageObj) => {
    console.log(imageObj, 'imageObj')
    const image = imageObj.imageBase64;
    await client.assets.upload("image", image, {contentType: imageObj.mimeType, fileName: imageObj.fullName});

Mar 28, 2022, 7:22 PM
but get 400 error
Mar 28, 2022, 7:23 PM
this the meta data, mimeType and fullName
Mar 28, 2022, 7:23 PM
Do you mind posting the error here as text rather than an image? Thanks!
Mar 28, 2022, 7:32 PM
Upload failed: Bad Request - Invalid image, could not read metadata
Mar 28, 2022, 7:34 PM
Can you upload this as a string or file type?
Mar 28, 2022, 7:44 PM
To be clear are you sending the base64 string to the asset upload or the file?
Mar 28, 2022, 7:44 PM
Per the assets documentation , you’ll need to convert that to a supported or tolerated image format, upload the blob as a string or file, and if you then want to view the string in the studio you’ll need to make a custom component to interpret it.
Though Sanity lets you import a wide range of image formats like TIFF and SVG our currently supported image formats for processed output are: JPEG, PNG and WebP.
GIF and SVG pass through the image pipeline untouched, but if you want them scaled they will need to be output as one of the three formats above.
Mar 28, 2022, 7:47 PM
user Y
Mar 28, 2022, 8:10 PM
So I need to convert the base64 string into a blob?
Mar 28, 2022, 8:10 PM
I had a similar issue but realized my base64 string had the header describing the image type (
) and that was causing problems. Once I stripped it off and converted it to a buffer (
_let_ uploadBuffer = _await_ Buffer.from(imageBase64, 'base64');
) the images uploaded just fine.
Mar 28, 2022, 9:24 PM
I was going to write "You need to use one of the asset types listed in the docs or you need to use the "file upload" to upload a blob/string etc" but if you have had positive outcome with base64
user S
then I would most certainly attempt that approach first,
user F
! Great point out Dan, thanks
Mar 28, 2022, 9:39 PM
i ended up using this package https://www.npmjs.com/package/blob-util
Mar 28, 2022, 10:38 PM
fixed the problem, thanks for the response and support though
Mar 28, 2022, 10:38 PM
cool plugin, thanks for the tip
Mar 28, 2022, 10:49 PM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the 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?