Sails JS check if upload file is sent

953 views Asked by At

When uploading files with Sails JS the server crashes if there is no file sent with the request, considering this to be the controller action:

function(req, res) {
  req.file('testFile').upload(function() {
    // do something...
  });
}

I have tried to check the headers, but there seems to be no difference between a file being sent or not.

I am looking for something like this:

function(req, res) {
  if(file sent) {
    req.file('testFile').upload(...);
  } else {
    // file was not sent, do something else
  }
}

Is there a way that I could achieve this behavior of uploading a file or not on the same API?

2

There are 2 answers

2
Alex J On

I think this is what you're looking for

req.file('testFile').upload(function (err, uploadedFiles){
  if (err) return res.send(500, err);

  return res.send(200, uploadedFiles);
});
0
Simon Fakir On

This does not exactly anwser your question, but at least it is a solution:

req.file('testFile').upload(function (err, uploadedFiles){
   if (err) return res.send(500, err);
   if (uploadedFiles.length < 1) {
      return res.badRequest('file missing or could not be uploaded');
   }
   return res.send(200, uploadedFiles);
 });

uploadedFiles contains an array of successfully uploaded files, it they were available.