I'm trying to upload an image when a form is submited, the problem comes when I try to send the image as a base64 to the upload endpoint.
// Form input for image uploads
<input
name="main_image"
type="file"
accept="image/jpg, image/png, image/jpeg, image/webp"
onChange={(event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function (event) {
console.log(event.target.result);
setFieldValue("main_image", event.target.result); // This is what I send to the backend
};
if (file && file.type.match("image.*")) {
reader.readAsDataURL(file); // I send it as Base64 to show the image in the website
}
}}
/>
When the form is submited it runs a function to start the image upload in the backend
// Backend function to upload image
const { image } = req.body;
const imgBuffer = Buffer.from(
image.replace(/^data:image\/(png|gif|jpeg);base64,/, ""),
"base64"
);
form.append("fileUpload", imgBuffer);
const response = await fetch(`${process.env.GRAPH_DOMAIN}/upload`, {
method: "POST",
headers: {
authorization: "auth token",
"Content-Type": "application/x-www-form-urlencoded",
},
body: form,
});
// Do stuff with the response
I've tried sending the image as a base64, but it doesn't work, the documentation only says to use fs.createReadStream('path/to/file.png')
for non URL images, and sending the image as base64 as a URL doesn't work either.
Link to GraphCMS documentation: https://graphcms.com/docs/api-reference/content-api/assets#upload-by-file