[HEADS UP]: I’m required to use a Server Page, othetwise I would I have used “client side” component with axios.
I’m trying to upload a file to my external express server. Whatsoever, when sending it to the API route, the req.files.file
is empty, undefined or simply blank.
I’d like to mention the file is detected when the action attribute is triggered after submitting the form. The console.log(avatar)
returns the following:
file: File {
size: 476026,
type: 'image/jpeg',
name: 'Delta-Force-Operator-in-a-Chinook_4x-scaled.jpg',
lastModified: 1716527617781
}
Whatsoever, the troubles I’m facing have to do with the Express server. I use a library called express-fileupload
and in order to get the files from the upcoming request, I need to do something like req.files.file
where file
is the name of your input.
exports.uploadObject = asyncHandler(async (req, res, next) => {
// Prevent execution of code if there is not file in request
console.dir(req.files);
if (!req.files || Object.keys(req.files).length === 0 || !req.files.file) {
return next(new ErrorResponse(`No file uploaded`, 400));
}
/*
YADAYADAYADA
*/
// Return object
res.status(201).json({
success: true,
data: "success"
});
});
});
});
The issue
No matter what I do, the server does not receive the file and this is what gets displayed on the terminal {}
, an actual emptpy object with not even field or values in it.
This is my form within a Server Page:
const upgradeAvatar = async (formData) => {
'use server'
const avatar = formData.get('file')
const rawFormData = {
userId: auth?.data?._id,
username: auth?.data?.username,
userEmail: auth?.data?.email,
onModel: 'User',
album: 'profile-avatars',
file: avatar,
}
// Output
console.log(rawFormData.file);
// My function to external API
await uploadFile(rawFormData)
}
<form action={upgradeAvatar}>
<label htmlFor="file" className="form-label">
File
</label>
<input
id="file"
name="file"
type="file"
className="form-control mb-3"
accept={`image/*`}
/>
<FormButtons />
</form>