Node.js 得到一个;makeError处出现意外字段“;上载表单时
我的表单有一个文件(在我的例子中是图像)和一些文本的输入。当我点击submit按钮时,出现了声明的错误。我已经有这个问题两天了,我试图了解问题所在,但我的努力徒劳无功,我决定让步并寻求帮助 这是我的图像控制器:Node.js 得到一个;makeError处出现意外字段“;上载表单时,node.js,mongodb,express,mongoose,multer,Node.js,Mongodb,Express,Mongoose,Multer,我的表单有一个文件(在我的例子中是图像)和一些文本的输入。当我点击submit按钮时,出现了声明的错误。我已经有这个问题两天了,我试图了解问题所在,但我的努力徒劳无功,我决定让步并寻求帮助 这是我的图像控制器: // using this to generate a random name for an image var possible = 'abcdefghijklmnopqrstuvwxyz0123456789', imgUrl = ''; // this is just a
// using this to generate a random name for an image
var possible = 'abcdefghijklmnopqrstuvwxyz0123456789',
imgUrl = '';
// this is just a loop to create a 10 character random name
for(var i = 0; i < 10; i++) {
imgUrl += possible.charAt(Math.floor(Math.random() *
possible.length));
}
/* I saw an answer to a similar question where the correct answer author
said path will always refer to folder where the input folder resides */
var tempPath = req.file.path,
ext = path.extname(req.file.path).toLower(),
targetPath = './app/controller/store/' + imgUrl + ext;
// Check if image is of the correct format
if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif')
{
fs.rename(tempPath, targetPath, function(err) {
if (err) throw err;
res.redirect('/posts/'+ imgUrl);
});
} else {
fs.unlink(tempPath, function () {
if (err) throw err;
res.json(500, {error: 'Only image files are allowed.'});
});
var post = new Post({
content: req.body.content,
author: req.user,
filename: imgUrl + ext
});
post.save(function(err) {
if(err) {
return res.status(400).send({
message: getErrorMessage(err)
});
} else res.json(post);
});
}
如果您能引导我走上正确的道路,我将不胜感激。谢谢您。single('parameter')表示输入字段的名称为'parameter'
就你而言:
app.use(multer({dest: './app/controller/store'}).single('photo'));
您将“photo”参数传递到单个func中
那么您的表单应该如下所示,更改它:
..
..
<input type="file" name="photo">
..
..
。。
..
..
..
app.use(multer({dest: './app/controller/store'}).single('photo'));
..
..
<input type="file" name="photo">
..
..