akromx
akromx

Reputation: 99

Req.files.file.length undefined when one file is uploaded

I'm working on a multiple files upload using Reactjs/Node.js/Expressjs.

I can upload multiple files to my uploads directory in my backend and to my database.

But when I try to upload only one file nothing happens.

On the Front the file is correctly selected and when I console.log(this.state.selectedFile.length) I got 1, it works.

But on the backend when I use console.log(myFile.length) I got undefined. If I upload 2 or more files the console.log shows the correct length and I don't know why.

My code (backend)

export const uploadFile = (req, res) => {
  const myFile = req.files.file;
  // upload file(s) to directory
  for (let i = 0; i < myFile.length; i++) {
    myFile[i].mv("./src/uploads/" + myFile[i].name, function(err) {
      if (err) {
        return res.status(500).send(err);
      }
    });
    // save file(s) to database
    Upload.create({
      type: myFile[i].mimetype,
      name: myFile[i].name,
      data: myFile[i].data
    });
  }
  console.log(myFile.length);
  res.send("files uploaded !");
};

If you want more code/explanations feel free to ask.

Upvotes: 1

Views: 800

Answers (2)

Renaud Reguieg
Renaud Reguieg

Reputation: 81

const myFile = (Array.isArray(req.files.file)?req.files.file:[req.files.file]).filter(e=>e);
    // filter is important, so that you have [] instead of [undefined] if req.files.file is undefined

Might do the trick because one file might be an object and more an array. so the trick is to reconsider non array for array

Upvotes: 2

KiraLeOuf
KiraLeOuf

Reputation: 23

Maybe if you have only 1 element the "req.files.file" is not an array ?

Upvotes: 0

Related Questions