天天看点

Busboy 上传文件到指定目录,并重命名,node.js

1,安装busboy ,在该项目下打开命令行(按住shift+右键)

npm install busboy
           

2,页面:必须含有(

enctype="multipart/form-data"
           

<form class="form form-signin" action="" method="post" id ="myForm" enctype="multipart/form-data">
        <h1 class="form-signin-heading">上传视频</h1>

        <label for="cName"  class="sr-only"></label>
        <input  id="cName" type="text" maxlength="40" placeholder="课程名称" name="lesson[name]" required autocomplete="false" autofocus />

        <label for="cNo"  class="sr-only"></label>
        <input type="number" id="cNo" name="lesson[no]" placeholder="目录(第几集)" />

    <div class="video">
        <span>添加视频</span>
        <input type="file" name="videoUpload"  id="cVideo"  accept="video/*" />
        <p class="vBackg"></p>
    </div>

    <input type="submit" value="上传课程视频" class="btn btn-primary btn-block submit" id="sub"/>
</form>
           

传参:

var lName = $('#cName').val(),
        lNo = $('#cNo').val();


       $('#myForm').attr('action', "/videoUpload?lName="+lName+"&lNo="+lNo) ;
           

3,后台处理:

3.1,获取前台post过来的参数:

req.query.XXX
           

其中XXX 就是传过来的参数名,比如localhost:3000?lName=joh,就是lName,获得的就是joh

3.2 处理

router.post('/videoUpload',function(req, res) {

    //在这里做一个头部数据检查
    if(!/multipart\/form-data/i.test(req.headers['content-type'])){
        return res.end('wrong');
    }
    var lName,
        lNo;
  /*
       db = mongoose.connect(db_url),*/
    var  filePath = path.join(path.normalize(__dirname + '/..'), 'public', 'upload');
    var busboy = new Busboy({ headers: req.headers });
/*    db.connection.on('open', function() {
        console.log('lesson db connected');
    });*/
    busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
        console.log('File [' + fieldname + ']: aaa filename: ' + filename);
        console.log('lName: ' + req.query.lName + "lNo: " + req.query.lNo);
        lName = req.query.lName;
        lNo = req.query.lNo;
        createFlo(lName, filePath);
        var type = mimetype.toString();
        var savePath = filePath + '\\' + lName + '\\' + lNo + '.' + type.substr(type.indexOf('/') + 1, type.length);
        showErr(savePath);

        file.pipe(fs.createWriteStream(savePath));
       Lesson.save({lessonName: lName, lNo: lNo, creTime: Date.now()}, function (err) {
           showErr(err);
       });

        console.log('插入数据库成功');

        file.on('data', function (data) {
            console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
        });
        file.on('end', function () {
            console.log('File [' + fieldname + '] Finished');
        });

    });
    busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
        console.log('Field [' + fieldname + ']: value: ' + inspect(val));
    });
    busboy.on('finish', function() {
        console.log('Done parsing form!');
        res.writeHead(200, { 'Connection': 'close' });
        res.end("That's all folks!");
    });
   return req.pipe(busboy);

});
function createFlo(lName,filePath){

    var dirpath =filePath+'\\'+lName;
    console.log("dirpath "+dirpath);
    //不存在文件夹,创建
    if (!fs.existsSync(dirpath)) {
        fs.mkdirSync(dirpath, 0755);
        console.log( '文件夹创建成功~');
    }
}
function  showErr(err) {
    console.log("info / err: "+ err);
}
           

还包括上传数据库的代码,大家也可以参考

继续阅读