VASU TIWARI
VASU TIWARI

Reputation: 768

How to upload file and json data at once in react and express

I want to send a file as well as JSON data from a form This is my react handle submission method.

const formData = new FormData();

formData.append('File', selectedFile);


const data = {
  name: 'vasu',
  email: '[email protected]',
  role: 'student'
}

formData.append('data', data);

axios.post('http://localhost:8000/users', formData ).then((result) => {
  console.log('Success:', result);
})
  .catch((error) => {
    console.error('Error:', error);
  });

And this Is my server.js method

app.post('/users', upload.single('File') , async (req, res) => {
    console.log(req.file , req.body);
    res.send(req.body);
})

and this is the output I get

{
   fieldname: 'File',
   originalname: '4eec81ebddc991f6ff017e600dbf58ac.png',
   encoding: '7bit',
   mimetype: 'image/png',
   destination: 'avatars',
   filename: 'File-4eec81ebddc991f6ff017e600dbf58ac.png-1620467341921',
   path: 'avatars\\File-4eec81ebddc991f6ff017e600dbf58ac.png-1620467341921',
   size: 426281
 } [Object: null prototype] { data: '[object Object]' }

i don't want this [Object: null prototype] { data: '[object Object]' } instead i want the JSON object i send i am also using

app.use(express.json())
app.use(express.urlencoded({extended: true}))

I am also using multer for file upload

Upvotes: 3

Views: 3831

Answers (1)

IAmDranged
IAmDranged

Reputation: 3020

This is what mdn says about the FormData append() method parameter:

This can be a USVString or Blob (including subclasses such as File). If none of these are specified the value is converted to a string.

The default string conversion which applies for javascript objects results in '[object Object]' - which explains the result you're seeing.

As per the multer documentation, besides files, their middleware actually seem to expect text content types as inputs, so this is probably for the better. Note the express body parsers do not support multipart/form-data content types - which is what is required for file uploads -, so they do not get involved with the parsing at all here.

You should just append each text input one by one to the formData object, and each will be available as a property on the req.body object:

formData.append('name', 'vasu')
formData.append('email', '[email protected]')
formData.append('role', 'student')

Upvotes: 2

Related Questions