4

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

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Tnx, was thinking the same, just wanted to check if there is any other way

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.