Uploading base64 images to Sanity and resolving a 400 error
16 replies
Last updated: Mar 28, 2022
J
I'm looking at the docs
Can I upload base64 to to sanity? or no
client.assets.upload(type: 'file' | image', body: File | Blob | Buffer | NodeStream, options = {}): Promise<AssetDocument>
Mar 28, 2022, 6:53 PM
J
I'm trying to upload base64 image to sanity
Mar 28, 2022, 7:22 PM
J
const handleOnSave = async(imageObj) => { console.log(imageObj, 'imageObj') const image = imageObj.imageBase64; setImageAsset(image); await client.assets.upload("image", image, {contentType: imageObj.mimeType, fileName: imageObj.fullName}); closeImgEditor(); }
Mar 28, 2022, 7:22 PM
J
but get 400 error
Mar 28, 2022, 7:23 PM
J
this the meta data, mimeType and fullName
Mar 28, 2022, 7:23 PM
B
Do you mind posting the error here as text rather than an image? Thanks!
Mar 28, 2022, 7:32 PM
J
Upload failed: Bad Request - Invalid image, could not read metadata
Mar 28, 2022, 7:34 PM
J
Can you upload this as a string or file type?
Mar 28, 2022, 7:44 PM
B
To be clear are you sending the base64 string to the asset upload or the file?
Mar 28, 2022, 7:44 PM
J
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
J
Yes
user Y
Mar 28, 2022, 8:10 PM
J
So I need to convert the base64 string into a blob?
Mar 28, 2022, 8:10 PM
D
I had a similar issue but realized my base64 string had the header describing the image type () the images uploaded just fine.
data:image/jpeg;base64,) and that was causing problems. Once I stripped it off and converted it to a buffer (
_let_ uploadBuffer = _await_ Buffer.from(imageBase64, 'base64');
Mar 28, 2022, 9:24 PM
B
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, thanksMar 28, 2022, 9:39 PM
J
i ended up using this package https://www.npmjs.com/package/blob-util
Mar 28, 2022, 10:38 PM
J
fixed the problem, thanks for the response and support though
Mar 28, 2022, 10:38 PM
J
cool plugin, thanks for the tip
Mar 28, 2022, 10:49 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.