具有Post方法和enctype的表单不在Nodejs Express multer模块上提交Multipart / form-data

时间:2017-05-06 11:21:54

标签: node.js forms express ejs multer

我正在使用:

"ejs": "^2.5.6",
"express": "^4.14.0",
"express-validator": "^3.2.0",
"multer": "^1.3.0",

我的表格是:

     <form id="offer-form" role="form" enctype="multipart/form-data" action="/subfolder/86" method="POST">
    <input type="text" name="name"/>
    <input type="file" name="images"/>
<input type="file" name="images"/>
    <button type="submit">Submit</submit>
    </form>

我的服务器路线:

var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var osmodule = require('../../osmodule');
var Multer = require('multer');
var request = require('request');
const multer = Multer({
    storage: Multer.memoryStorage(),
    limits: {
        fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
    }
});


  //Adding a new subfolder
        app.post('/subfolder/:id', multer.array({ name: 'images', maxCount: 6 }), expressValidator, function (req, res, next) {
console.log("Form Submitted");
       }).use(function (req, res, next) {
    res.setHeader('Content-Type', 'text/plain');
    res.status(404).send('Not Found ! ');
    });

通常此代码应在控制台上打印消息

  

提交表格   但服务器甚至没有收到任何东西   找不到

我刚刚注意到问题在于使用multer和expressValidator。如果我删除了expressValidator,它正在工作,但如果我添加它,它就无法正常工作。我需要expressValidator来验证用户数据。是否有其他验证器可以接受与multer一起使用?

1 个答案:

答案 0 :(得分:1)

我找到了使用这两个中间件的解决方案,我只是在操作之前调用了它,并在调用multer之后调用了express-validator:

var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var osmodule = require('../../osmodule');
var Multer = require('multer');
var request = require('request');
const multer = Multer({
    storage: Multer.memoryStorage(),
    limits: {
        fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
    }
});

app.get('/home',function(req,res){
console.log("Welcome Brother");
})
.use(multer.array({ name: 'images', maxCount: 6 });
.use(expressValidator);
.post('/subfolder/:id', function (req, res, next) {
console.log("Form Submitted");
       }).use(function (req, res, next) {
    res.setHeader('Content-Type', 'text/plain');
    res.status(404).send('Not Found ! ');
    });