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);
}
還包括上傳資料庫的代碼,大家也可以參考