busboy上传问题
发布于 3 个月前 作者 maochunguang 304 次浏览 来自 问答

使用busboy进行图片上传,表单其他字段怎么获取,

exports.userSet = function (req, res, next) {
    //1、验证字段
    //2、上传
    var photo = '';
    var busboy = new Busboy({ headers: req.headers });
    busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
        //这里是设置下载后目录的(我是这样理解的,实际也是这样,若有不对的欢迎指正)
        var saveTo = path.join(__dirname, '../public/uploads', path.basename(filename));
        photo = saveTo;
        file.pipe(fs.createWriteStream(saveTo));
    });
    busboy.on('finish', function () {
		  var school = req.body.school;
		  var user_id = req.body.user_id;
		  var hobby = req.body.hobby;
		  console.log('school= ' + school);
        UserSet.newAndSave(user_id, photo, hobby, school, function (err) {
			  if (err) {
				  return next(err);
			  }
			  res.redirect('/');
        });
    });
    return req.pipe(busboy);
}
\n``` 
怎么从req,body拿到其他的字段啊
6 回复

req.body中没有school和hobby字段的值,为什么

这样排版没人愿意回答

@i5ting 谢谢建议,已经修改了排版

busboy.on(‘file’, function (fieldname, file, filename, encoding, mimetype) { //我想应该是在这个事件里面获取吧‘ req.body.fieldname 看看吧,这个如果有多个字段,建议加个是否是文件域判断
});

##应该这么用,

var inspect = require('util').inspect;
 var Busboy = require('busboy');
var validator = require('validator');

exports.upload = function(req, res){
 busboy.on('field', function (fieldname, val) {
        if (fieldname == 'school')
            var school = validator.trim(inspect(val));
        if (fieldname == 'hobby')
            var hobby = validator.trim(inspect(val));
    });
} 
#可以试试
回到顶部