Need to Convert Image to Buffer for Storage
Answered
Gull Dong posted this in #help-forum
Gull DongOP
I am trying to convert my image which should be a file or blob type object into bytes encoded as base64 string.
Answered by Blizzard
Example, this is what I do
const handleNewPostSubmit = () => {
const form = new FormData();
if (post.image) form.append("image", post.image);
form.append("description", post.description);
fetch("/api/post", {
method: "POST",
body: form,
});
};19 Replies
may i ask why you're not using formdata to post the image?
Gull DongOP
i tried to and for whatever reason formData wasnt working in my code
Example, this is what I do
const handleNewPostSubmit = () => {
const form = new FormData();
if (post.image) form.append("image", post.image);
form.append("description", post.description);
fetch("/api/post", {
method: "POST",
body: form,
});
};Answer
Gull DongOP
im pretty sure when i did try to send it as formData it would appear as undefined
if you do that. make sure to change
await res.json() to await res.formData()if you try sending the File object to a route handler by trying to use JSON.stringify(), it wont work
yeah that's what I was thinking
because it wont get serialized in the first place
check your data you are receieving in your route handler.
the image field will be empty
export async function POST(request: NextRequest) {
const form = await request.formData();
const image = form.get('image');
const buffer = Buffer.from(await image.arrayBuffer());
}^ that might work.
There are other ways but you basically have to read the buffer and stuff
@Blizzard javascript
export async function POST(request: NextRequest) {
const form = await request.formData();
const image = form.get('image');
const buffer = Buffer.from(await image.arrayBuffer());
}
Gull DongOP
@BlizzardI know it's been a minute since your response but I've encountered multiple issues:
1) form.get('image') returns an empty object {}
2) arrayBuffer() does not exist on type FormDataEntryValue
3) Buffer.from() most likely does not work because of form.get() returning empty
1) form.get('image') returns an empty object {}
2) arrayBuffer() does not exist on type FormDataEntryValue
3) Buffer.from() most likely does not work because of form.get() returning empty
Gull DongOP
Turns out logging the formData gave me false ideas about what was happening in the code. The issue is now getting the database to save the file from the form rather than it's object type. I suppose the issue is resolved.
well uh
it's probably better to save the image in s3/vercel blob/cloudinary than storing it in a database
Gull DongOP
id rather it only had the encoded url