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

我是研究僧i 提交于 2019-12-06 05:59:25

问题


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


回答1:


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

if (req._fileparser.upstreams.length) { /* upload code */ }


来源:https://stackoverflow.com/questions/28185223/sails-js-how-to-know-if-the-request-contains-a-file-to-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!