Input OnChange calling server action returning an error for a file upload.
Answered
Japanese Bobtail posted this in #help-forum
Japanese BobtailOP
Hi team! I have a server action being called on an input change for a file upload. However I'm getting
it does console.log the file correctly inside the server action. Is anyone please able to spot the error?
Error: Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported.it does console.log the file correctly inside the server action. Is anyone please able to spot the error?
export async function uploadFile(formData: any) {
const session = await getServerSession(authOptions);
console.log(formData)
try {
const response = await fetch(`/admin/upload-image`,
{
method: "POST",
body: formData,
headers: {
"Content-Type": "multipart/form-data",
"api-key": process.env.API_KEY!,
"Authorization": `Bearer ${session.jwt}`
}
})
return response.json()
} catch (error) {
return error
}
}Answered by Japanese Bobtail
It was the
return error. It wasn't a serializable object. Thank you GPT!! https://discord.com/channels/752553802359505017/1174078250637598821/11740783221588706644 Replies
try this
<input
type="file"
name="file"
onChange={(e) => {
if (e.target.files?.length) {
const formData = new FormData();
formData.set("file", e.target.files![0]);
uploadFile(formData);
}
}}
/>Japanese BobtailOP
I'm doing so already 😦
On the client:
async function uploadImage(data: any) {
setLoading(true);
if (data.target.files[0]) {
const formData = new FormData();
formData.append("image", data.target.files[0]);
const response = await uploadFile(formData);
if (response.message) {
toast({
title: "Erro",
description: response.message,
variant: "destructive",
});
} else {
toast({
title: "Imagem carregada com sucesso",
});
setValue(name, response.data);
}
setLoading(false);
}
}Japanese BobtailOP
It was the
return error. It wasn't a serializable object. Thank you GPT!! https://discord.com/channels/752553802359505017/1174078250637598821/1174078322158870664Answer