0

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;
Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35

1 Answers1

0

You can remove the content type from the Axios headers and let Axios set it by itself.

const onSubmit = async (data: any) => {
        const image = data.file[0];
        const params: RequestInit = {
            method: 'POST',
            body: JSON.stringify(data)
        };
        await fetch('/api/post/create-post', params);
        // Upload image to S3 Bucket
        // Save post to db
    }

You can check this link for the boundaries error.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
  • In the boundary isn't supposed to go the extra data I want to send? `description` for example? –  Jan 05 '22 at 15:55