我正在使用Multer在keystone环境中解析多部分表单,并且无法访问路由控制器中的req.body和req.file数据
路由/ index.js
var keystone = require('keystone'),
middleware = require('./middleware');
var bodyParser = require('body-parser');
//multi-part form parser for FTP api
var multer = require('multer');
var storage = multer.memoryStorage();
var upload = multer({storage: storage});
exports = module.exports = function(app) {
app.use(bodyParser.json({limit: '10mb'}));
app.use(bodyParser.urlencoded({limit: '10mb', extended: true}));
app.post('/upload_api', upload.single('formFile'), routes.api.uploadFTP);
};
路由/ API / uploadFTP.js
var keystone = require('keystone');
var ftpMod = require('ftp');
var fs = require('fs');
exports = module.exports = function(req, res) {
console.log("req.body is ");
console.log(req.body);
console.log("req.file is ");
console.log(req.file);
res.send("console.log() outputted to screen");
}
公共/测试upload.html
<html>
<body>
<form name="sampleForm" enctype="multipart/form-data" action="/upload_api" method="post">
<p>Method</p>
<input type="text" name="method"><br>
<p>Options</p>
<input type="text" name="options"><br>
<p>File</p>
<input type="file" name="formFile"><br><br>
<input type="submit" value="Click to Send">
</form>
</body>
</html>
我从nodejs收到的回复是
>req.body is
{}
req.file is
undefined
我希望req.body
包含{method:“sometext”}
并填充req.file
答案 0 :(得分:0)
您无法在req.body
或req.file
中获取值。用下面给出的代码替换你uploadFTP.js。
var multer = require('multer');
var path = require('path');
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, <<path where you want to store your files>>);
},
filename: function(req, file, callback) {
callback(null, path.basename(Date.now() + '_' + file.originalname));
},
});
var maxSize = 1024 * 1024;
var upload = multer({
storage: storage,
fileFilter: function(req, file, callback) {
var ext = path.extname(file.originalname);
if(ext !== '.gif' && ext !== '.jpeg') {
return callback(res.status(202).end();, null);
}
callback(null, true);
},
limits: {fileSize: maxSize},
}).single('image');
exports = module.exports = function (req, res) {
upload(req, res, function(err) {
console.log(storage.diskStorage);
if(err) {
return res.status(201).end();
}
//Do stuff here
res.status(200).end();
});
}
替换index.js中的以下行
app.post('/upload_api', upload.single('formFile'), routes.api.uploadFTP);
与
app.post('/upload_api', routes.api.uploadFTP);