Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sails.js: How to know if the request contains a file to upload?

I have the next action in one of my controllers, its function is upload a image file or create a new cover model using a video url, its work fine but when the request has a header Content-Type: multipart/form-data and does not contains a file the action throw a timeout error in req.file().

upload: function(req, res) {
    res.setTimeout(0);

    function onCreateCover(err, cover) {
        if (err) {
            return res.negotiate(err);
        } else {
            res.status(201);
            return res.json(cover);
        }
    }

    if (/^multipart\/form-data/.test(req.headers['content-type'])) {
        req.file('image').upload({
            maxBytes: 2000000,
            dirname: coverDir
        }, function(err, uploadedFile) {
            if (err) {
                res.serverError(err);
            } else if (uploadedFile.length > 0) {
                Cover.create({
                    title: req.body.title,
                    description: req.body.description,
                    path: uploadedFile[0].fd
                }).exec(onCreateCover);
            }
        });
    } else {
        Cover.create(req.body).exec(onCreateCover);
    }
}

I want to know if exist a method or way to check if request really contains a file

like image 781
Jaime Suncin Avatar asked Dec 24 '22 23:12

Jaime Suncin


1 Answers

I don't know if there is a better way, but I use this:

if (req._fileparser.upstreams.length) { /* upload code */ }
like image 87
hlozancic Avatar answered Mar 08 '23 14:03

hlozancic