Yogesh k
Yogesh k

Reputation: 352

Check for req.files object empty

I am uploading file through express-fileupload. My file gets uploaded successfully if I am not checking for req.files as empty. But I am getting one error as when I am going to check for req.files as empty. I am posting my code as referenace.

if(req.files.length > 0){

    console.log('file is exist');

    var file_name = req.files.filetoupload;

    file_name.mv("public/uploads/"+ file_name.name, function(err){
        if(err){
            console.log(err);
            var profile_pic_name = '';
        } else {
            var profile_pic_name = file_name.name;
        }
    });
}
else
{
    console.log('file not exist');
    var profile_pic_name = '';
}

So when I am trying to upload a file it goes in else section and prints "file not exist" on console. So my main concern is how to check if req.files is empty or not.

Thanks in advance

Upvotes: 4

Views: 5125

Answers (5)

Ajay Kumar Prasad
Ajay Kumar Prasad

Reputation: 85

You can do this

 const uploadPhoto = req.files.photo ? `images/${req.files.photo[0].filename}` : "";

Upvotes: 0

George Prethesh
George Prethesh

Reputation: 18

try {
  var file_name = req.files.filetoupload;

  file_name.mv("public/uploads/"+ file_name.name)
} catch (error) {
  res.send(`File not found`)
}

Use the try and catch method and it works...

Upvotes: 0

eliarms
eliarms

Reputation: 859

You can easily achieve that using a conditional ternary operator.
For instance, below sample code print "Non Empty File" if req.files exists or "Empty file" if req.files is empty.

req.files ? console.log('Non Empty File') : console.log('Empty file');

Upvotes: 2

viswanath608
viswanath608

Reputation: 155

You can do something like this and find out if the file exists or not.

if (!req.files) {
  // File does not exist.
  console.log("No file");
} else {
  // File exists.
  console.log("File exists");
}

Upvotes: 0

Nicolas Takashi
Nicolas Takashi

Reputation: 1740

Sorry I don't know if I understood correctly your question.

Try something like that:

req.files && req.files.length

I hope this help, If this doesn't meet your necessity let me know

Upvotes: 3

Related Questions