Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multer upload file + JSON object

Is it possible to send additionally to the file and json object containing data with multer? I found this thread. But it only explains how to attach one field at the time.

Here what i have currently on client side:

request
  .post(uploadPOSTUrl)
  .set('Accept', 'application/json')
  .field('Test', object.TestField)
  .attach('file', file)
  .end((err, res) => {
    if (err) {

    } else {

    }
  });

and server side

 export function upload(req, res){
    console.log("UploadedJSON: ", req.body);
    console.log("UploadedFile: ",req.file); 
    res.status(204).end();
}

but instead of just sending 1 field. I need to send the whole object .field('Test', object). When i do this, i receive [Object object] on the server side and can't access the fields.

My only solution right now would be to loop and add .field() for every field in my object...

like image 778
Daniel Storch Avatar asked May 27 '26 10:05

Daniel Storch


1 Answers

Your client-side code looks like it uses the SuperAgent library, am I right? If so, the real question is how to send multipart requests using SuperAgent, since multer only processes multipart/form-data.

The SuperAgent documentation for multipart requests shows the way you do it is to repeat the .field() method:

 request
   .post('/upload')
   .field('user[name]', 'Tobi')
   .field('user[email]', '[email protected]')
   .attach('image', 'path/to/tobi.png')
   .end(callback);
like image 61
Nocturno Avatar answered May 30 '26 07:05

Nocturno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!