我的表单有一个文件输入(在我的例子中是一个图像)和一些文本。当我点击提交按钮时,会出现所述错误。我已经有两天这个问题,我试图了解问题所在,但我的努力是徒劳的,我决定屈服并寻求帮助。
这是我的图像控制器:
// 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);
});
}
以下是表格:
<form method="post" action="/posts" enctype="multipart/form-data">
<textarea name="content"></textarea>
<input type="file" name="file" id="file">
<input type="submit" value="Post">
</form>
我在配置文件中执行了常用的操作:
app.use(multer({dest: './app/controller/store'}).single('photo'));
如果你引导我走向正确的道路,我会非常感激,感谢提前。
答案 0 :(得分:0)
.single(&#39;参数&#39;)表示输入字段的名称是&#39;参数&#39;
在你的情况下:
app.use(multer({dest: './app/controller/store'}).single('photo'));
你通过了一张照片&#39;单个函数的论证。
然后你的表格应该是这样的,改变它:
..
..
<input type="file" name="photo">
..
..