Is there a way I can attach some content for each file that I send to the server?
For now, I am using the following code
const formData = new FormData();
files.forEach((file) => {
  formData.append('files[]', file);
});
This is a part of the form submit method, now, each file can have some description. Is there any way I can add that additional data to the file and handle it in the same form data, without sending a separate request for each file?
On the server, I am using multer to access those files. Maybe there is something else that it is not a FormData where the files can be sent
You do not need to send a separate request to send title of file. You can send 2 arrays of identical size and parse those two at the same time getting file from one and title from the other
const upload = async () => {
  try {
    const file = fs.createReadStream('./myfile.txt');
    const title = 'My file';
  
    const form = new FormData();
    form.append('title', title);
    form.append('file', file);
  
    const resp = await axios.post('http://localhost:3000/upload', form, {
      headers: {
        ...form.getHeaders(),
      }
    });
  
    if (resp.status === 200) {
      return 'Upload complete';
    } 
  } catch(err) {
    return new Error(err.message);
  }
}
upload().then(resp => console.log(resp));
on the other side you can extract it by
var express = require('express');
var router = express.Router();
const multer  = require('multer');
const upload = multer({ dest: os.tmpdir() });
router.post('/upload', upload.single('file'), function(req, res) {
  const title = req.body.title;
  const file = req.file;
  console.log(title);
  console.log(file);
  res.sendStatus(200);
});
module.exports = router;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With