I was trying a few weeks ago to upload an image to my NodeJS server and, from there, save it to an S3 bucket, but I'm stuck on the first part and my server doesn't receive the image. I'm using multer
for saving it in the public/
folder.
This is what I have in my client:
const onSubmit = async (data: any) => {
const image = data.file[0];
const params: RequestInit = {
method: 'POST',
headers: {
'Content-Type': `multipart/form-data`,
'Accept': 'image/*'
},
body: JSON.stringify(data)
};
await fetch('/api/post/create-post', params);
// Upload image to S3 Bucket
// Save post to db
}
I was setting a boundary in the Content-Type
with data=${JSON.stringify(data)}
, and when I log the headers of my request before trying to save the image, there is no "boundary" and instead I receive this error Error: Multipart: Boundary not found
(This error is shown in my server console)
And this is what I have in my server:
const upload = multer({
dest: 'public/'
})
const router = express.Router();
router.post('/', (req, res, next) => {
console.log(req.headers);
next();
}, upload.single('photo'), (req, res) => {
console.log(req.file);
res.json({ success: true });
})
module.exports = router;