TonyW
TonyW

Reputation: 18875

How to tell if a POST request contains files for uploading in Sails.js?

I use sails.js for creating a backend, and it supports posting text and uploading file/image same time in one of my controller methods. Because of the business logics, I need to tell if a POST request to this controller method contains file for uploading or not.

To upload files, I use the build-in Skipper module in sails.js and use the file field in the req parameters. For example, if I need to upload images, I put images field in the request going to the backend/sails.js:

req.file('images').Upload({...}); 

I tried to use req.file('images') to examine if the incoming request contains files to upload by following, but it does not work - request without uploading files still gives req.file('images') = true:

if (!!req.file('images')) { // this turns out to be true regardless of uploading file or not
            return uploadToS3(req, 'images');
        }

sails.log.info('creating entity without uploading file');
return createEntityWithoutImage(req.params.all());

Any idea how to tell if a POST request contains file to upload?

Upvotes: 1

Views: 695

Answers (1)

Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24600

You can check number of files that the user uploaded by using:

req.file('images')._files.length

This is undocumented feature of skipper:

https://github.com/balderdashy/skipper/blob/master/standalone/Upstream/Upstream.js#L51

So it can be decpreate in future versioln. So be sure, that you not upgrade the module without testing it first.

Upvotes: 1

Related Questions