###文件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个多星期了,一致没解决!真心谢谢
你可以试一下multiparty,你如果只用bodyParser是不支持事件的。
我也是初学,当时研究上传也搞不懂。如果用第三方插件,记得把defer开起来,不然请求就全部都在bodyParser 这里了。
可阅读node高级课程 《Node服务器框架开发实战》
QQ群 244728015
没看,看不了!!!
能不能给我一个小例子啊,看了半天还是不太明白
上面就有例子啊
请问解决了吗?
我也是遇到同样的问题,不知所措啊
原来是这样的:
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');
});
});
});
});