###文件App.js中的express上传设置
app.use(express.bodyParser({ uploadDir:"public/images", keepExtensions : true, limit:100000000, defer:true }));
###上传html
<form method="post" enctype="multipart/form-data" action="/upload"> <input type="text" name="username"> <input type="password" name="password"> <input type="file" name="pic"> <input type="submit"> </form>后台接受
exports.upload = function (req, res) {
console.log(req.body);
req.form.on('progress', function(bytesReceived, bytesExpected) {
console.log(((bytesReceived / bytesExpected)*100) + "% uploaded");
});
req.form.on('end', function() {
console.log(req.files);
var picName = req.files.pic.name;
fs.rename(req.files.pic.path, "./public/images/pics/" + picName, function (err) {
if (err) throw err;
fs.unlink(req.files.pic.path, function () {
if (err) throw err;
//res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes');
});
});
res.send("done");
});
}
点击上传, console.log(req.body) 的结果是 {} ,空 文件pic null;
求大神帮忙,2个多星期了,一致没解决!真心谢谢
11 回复
原来是这样的:
app.use(express.bodyParser({uploadDir:’./tmp’})); //一定要放在app.use(app.router);前面 app.use(app.router);
找了好久才找到原因。。。
@sihao1234 照你说的写
app.use(express.bodyParser({uploadDir:'./tmp',keepExtensions : true, limit:100000000, defer:true }));
app.use(express.static(__dirname + '/public'));
app.use(app.router);
控制台显示 {} 24.552031461820327% uploaded 50.02751567050991% uploaded 到这里就死了不动了
貌似 req.form.on(‘end’ 根本就不执行
app.post('/upload', function (req, res) {
console.log(req.body);
req.form.on('progress', function(bytesReceived, bytesExpected) {
console.log(((bytesReceived / bytesExpected)*100) + "% uploaded");
});
req.form.on('end', function() {
console.log('end .... ');
// console.log(req.files);
var picName = req.files.pic.name;
console.log('end .... '+req.files.pic.path +'--->'+ "public\\images\\pics\\" + picName)
fs.rename(req.files.pic.path, "public\\images\\pics\\" + picName, function (err) {
if (err) throw err;
console.log('unlink');
fs.unlink(req.files.pic.path, function () {
if (err) throw err;
res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes');
});
});
});
});