<form action="/upload" method="POST" enctype="multipart/form-data">
<fieldset>
<span>Event name</span>
<input name = "name" type="text" class="form-control" value="<%= `${event.name}` %>" readonly>
</fieldset>
<fieldset>
<span>File</span>
<input name = "eventImage" type="file" class="form-control" id="name" placeholder="Event name..." required>
</fieldset>
<fieldset>
<button type="submit" id="form-submit" class="btn">Add Event</button>
</fieldset>
</form>
而且第一个 console.log(req.body.name) 越来越不确定...... 我如何解决这个问题?
app.post("/upload", (req, res) => {
console.log(req.body.name); // output is undefined
const storage = multer.diskStorage({
destination: './public/images' + req.body.name,
filename: function(req, file, cb){
cb(null, file.originalname);
}
});
const upload = multer({
storage: storage,
}).single('eventImage');
upload(req, res, (err) => {
if(err){
console.log(err);
}
else{
console.log(req.body.name); // output is correct
console.log(req.file);
}
})
});
第一个console.log(req.body.name)输出为undefined,而其他console.log都显示正常,如何解决?
试试用这个。
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false })) // urlencoded
app.use(bodyParser.json()) // json
...
...
app.post("/upload", (req, res) => {
console.log(req.body.name);
console.log(req.file);
});
我有一个类似的问题,我已经解决了,通过 通过一个隐藏的输入值 但仍然保留readonly字段,以便用户可以看到数据。
<form action="/upload" method="POST" enctype="multipart/form-data">
<fieldset>
<span>Event name</span>
<input name="display_name" type="text" class="form-control" value="<%= `${event.name}` %>" readonly>
<input name="name" type="hidden" value="<%= `${event.name}` %>">
</fieldset>
<fieldset>
<span>File</span>
<input name = "eventImage" type="file" class="form-control" id="name" placeholder="Event name..." required>
</fieldset>
<fieldset>
<button type="submit" id="form-submit" class="btn">Add Event</button>
</fieldset>
</form>
然后检查你的结果
app.post("/upload", (req, res) => {
console.log(req.body.name);
console.log(req.file);
});