Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Send multiple files with additional data for each file Javascript, NodeJS

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading