Expressjs分段上传失败但POST仍然存在

时间:2017-03-02 02:36:10

标签: node.js express multer

我遇到一个问题,即error函数中的upload()语句被触发,但没有停止处理表单提交并发送重定向,如我的if语句的错误一半所示。我的.post路由中缺少哪些路径允许剩余的路由方法运行?

上传变量定义中的非法文件扩展名格式是引发错误的原因。

发表

.post(function(req, res){
        var s3FilePath = [];

        upload(req, res, function(err){
            if(err){
                req.flash('error', err);
                res.redirect(req.get('referer'));
            }

            var uploadedFiles = req.files;

            //Configure Uploaded S3 File Path strings based on environment for use in DB
            for (var prop in uploadedFiles){
                console.log(uploadedFiles[prop].key);
                if (app.get('env') === 'production' || app.get('env') === 'staging'){
                    s3FilePath = 'https://files.test-site.com/' + uploadedFiles[prop].key;
                } else {
                    s3FilePath.push(uploadedFiles[prop].location);
                }
            }

            models.Blog.create({
                title: req.body.title,
                type: req.body.type,
                userId: req.user.userId     
            }).then(function(blog){
                var files = _.map(s3FilePath, function (file) {
                    return {
                        file: file,
                        blogId: blog.blogId
                    };
                });
                return models.BlogFile.bulkCreate(files); 
            }).then(function(){
                req.flash('info', 'Blog was successfully created.');
                res.redirect('/app');
            });
        });
    });

upload变量定义:

   var upload = multer({
        storage: multerS3({
            s3: s3,
            bucket: options.Bucket,
            contentType: multerS3.AUTO_CONTENT_TYPE,
            acl: options.ACL,
            key: function(req, file, cb){
                var fileNameFormatted = file.originalname.replace(/\s+/g, '-').toLowerCase();
                cb(null, req.user.organizationId + '/' + uploadDate + '/' + fileNameFormatted);
            }
        }),
        fileFilter: function(req, file, cb){
            if(!file.originalname.match(/\.(jpg|jpeg|png|gif|csv|xls|xlsb|xlsm|xlsx)$/)){
                return cb('One of your selected files is not supported', false);
            }
            cb(null, true);
        }
    }).array('fileUpload', 5);

1 个答案:

答案 0 :(得分:1)

重定向后添加一个return语句。记住脚本是必不可少的,它将继续执行。或使用res.end()来终止所有后续请求。

  if(err){
            req.flash('error', err);
            res.redirect(req.get('referer'));
            return;
        }

重定向调用不会改变代码的状态流,它只会修改路由,因此执行下一行var uploadedFiles = req.files;这是非法的,并抛出非法的文件扩展名格式。