I’m learning about file upload flow between Nextjs app and third party api (in this case an Express server).
The flow suppose to go like this:
1.The user upload an image file via <input type="file">
then press submit which trigger server action (React’s useFormState hook).
2.The server action receives formData
object which contains the uploaded file. Now this is where I’m not sure if I did right. I want to upload the file inside the formData object to an Express app (which would then be processed and saved on a disk). So I used the following logic.
Next.js server action
export async function uploadImage(prevState, formData) {
const imageFile = formData?.get("image");
if (!imageFile) {
return { success: false };
}
try {
const response = await axios.post(
"http://localhost:3002/uploadimages",
formData,
{
headers: {
"Content-Type": "multipart/form-data",
},
}
);
return { success: true };
} catch (error) {
console.error("Error uploading image:", error);
return { success: false };
}
}
Express.js endpoint with multer
app.post('/uploadimages', upload.single('image'), (req, res, next) => {
res.status(201).json({
message: 'Image uploaded successfully'
});
});
Now the problem is every time I upload an image file this way, the server received the request but it hanged. The file seemed to show up in a directory I specified in multer setup. But all the files seem to be incomplete. The images were either blurred or partly missing.
I tried testing the endpoint with pure HTML, it works fine, the image showed up.
Is there specific behavior of Next.js that cause this?
Lancero Voloce is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.