In my frontend I'm using input[type='file'] to get image data from the users, and POST to my API. In the backend, I'm parsing the data using formidable. The issue is that uploadImage Api returns input buffer contains unsupported image format.
Note** -> I can upload the file to sanity cdn directly from the frontend, but it expose my token in the browser, and sanity don't prefer it.
frontend->
export default function Component() {
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const file = e.currentTarget[0]?.files[0];
const formdata = new FormData();
formdata.append("file", file);
fetch("/api/uploadImage", {
method: "POST",
body: formdata,
})
.then((res) => res.json())
.then((r) => console.log(r))
.catch((err) => console.log(err));
};
return (
<div>
<form encType="multipart/form-data" onSubmit={handleSubmit}>
<input type="file" id="inputFile" name="avatar" />
<button
type="submit"
className="rounded-md bg-indigo-500 px-4 py-1 text-white"
>
Select some files
</button>
</form>
</div>
);
}
backend->
export const config = {
api: {
bodyParser: false,
},
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const data = await new Promise((resolve, reject) => {
const form = formidable();
form.parse(req, (err, fields, files) => {
if (err) {
reject(err);
}
resolve({ req, fields, files });
});
});
const { fields, files } = data;
try {
const { _id } = await client.assets.upload("image", files);
res.status(200).json(_id);
} catch (err) {
res.status(400).send(err);
}
}
files
, an array? Does client.assets.upload work with an array of files?