【发布时间】:2017-09-30 12:56:01
【问题描述】:
我在我的 NodeJS 应用程序中使用 body-parser、express 和 multer。
我需要在注册表单中上传图片和几个文本字段。我为此使用multer,我尝试了与here建议完全相同的东西
但我在req.body 中得到了空对象。
正在目标文件夹中创建文件,但 req.files.forEach 方法记录空结果。
这是我的代码:
HTML前端代码
<form id="form" enctype="multipart/form-data" action="/profile" method="post" >
<label>Name</label>
<input type="text" placeholder=" Name" name="name" id="name" class="form-control">
<label>Logo</label>
<input type="file" placeholder="Logo" name="logo" id="logo" class="form-control">
<button id="addform" type="submit" class="btn btn-primary">Add Profile</button>
</form>
服务器端代码:
app.post('/profile', function(req, res) {
var storage = multer.diskStorage({
destination: __dirname+'/file/uploads/'
});
var upload = multer({ storage : storage}).any();
upload(req,res,function(err) {
if(err) {
console.log(err);
return res.end("Error uploading file.");
} else {
console.log(req.body);
console.log(req.files);
req.files.forEach( function(f) {
console.log(f);
// and move file to final destination...
});
res.end("File has been uploaded");
}
});
});
节点中的日志输出:
{}
[]
【问题讨论】:
-
我已经复制了确切的代码并尝试了它。身体和记录到控制台的文件一切正常。那么,也许是其他代码的问题?也许是中间件?希望这会有所帮助。
-
您的问题解决了吗?
-
是的,实际上我在引用按钮单击时忘记添加“#”。
-
请将其标记为答案。
标签: javascript node.js express multer