Cannot send any data with FormData Javascript

Viewed 34

This is my script code:

  let formData = new FormData();
  var file_data = Array.from($('#file1').prop('files')).concat(Array.from($('#file2').prop('files')).concat(Array.from($('#file3').prop('files'))));
  $.each(file_data, function (index, value) {
    formData.append('file' + index, value);
  });
  $.ajax({
    url: "/registerFullData",
    type: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    success: function (data) {
      // some actions..
    }
  });

And this is backend code:

router.post('/registerFullData', async (req, res) => {
  const files = req.files;
  const body = req.body;
  console.log(files);
  console.log(body);
}

Both of them are empty. If i use an simply object with keys and values(no file) and without processData and contentType attributes i reveice all my data.

What i am doing wrong?

1 Answers

Problem solved using formidable library.

let form = new formidable.IncomingForm();
form.parse(req, function (error, fields, file) {
 console.log(file);
 console.log(fields);
 let filepath = file.propicUrlFile.filepath;
 let newpath = './public/assets/images/asd/';
 newpath += file.propicUrlFile.originalFilename;
 try {
   fs.rename(filepath, newpath, function () {
     //action here
   });
 } catch (error) {
     //action here
 }
});
Related