我有一个用于食品自动化系统的CMS,我将为食品上传图片添加一部分:
<form method="post" enctype="multipart/form-data" action="/upload">
<td><input class="styleFormForAddProducts foodpicForAddFood" type="file" name="file"></td>
<td><input class="styleFormForAddProducts submitForAddFood" type="submit" value="Submit" ></td>
</form>
我在Express.js中编写了用于发出POST请求的代码:
app.post('/upload', function (req, res) {
var tempPath = req.files.file.path,
targetPath = path.resolve('./uploads/image.png');
if (path.extname(req.files.file.name).toLowerCase() === '.png') {
fs.rename(tempPath, targetPath, function(err) {
if (err)
throw err;
console.log("Upload completed!");
});
} else {
fs.unlink(tempPath, function () {
if (err)
throw err;
console.error("Only .png files are allowed!");
});
}
});
但是当我定义这个app.use
时,我收到一个错误:
中间件:app.use(express.bodyParser({uploadDir:&#39; / img&#39;}));
错误:错误:大多数中间件(如bodyParser)不再与Express捆绑在一起,必须单独安装。请参阅https://github.com/senchalabs/connect#middleware。
当我定义这样的中间件时:
app.use(bodyParser({uploadDir:'/img/'}));
我没有任何错误,但我的代码无法正常运行。
答案 0 :(得分:0)
这个解决方案对我有用:
multer = require('multer'),
upload = multer({ dest: 'views/img' });
app.post('/upload',upload.single('file'), function (req, res) {
});
我的表单HTML
形成:
<form method="post" enctype="multipart/form-data" action="/upload">
<input class="styleFormForAddProducts foodpicForAddFood" type="file" name="file">
<input class="styleFormForAddProducts submitForAddFood" type="submit" value="Submit" >
</form>