我對Node.js相當陌生,我使用Express和Busboy-Connect來創建一個簡單的文件上傳表單,僅用於wav文件。 下面是我想要做的: - 開始上傳 - 如果mimetype不是wav,重定向到錯誤頁面 - else:在服務器上寫入文件並重新導向回。如果mime類型無效,如何停止在busboy中上傳和重定向?
如果mimetype是有效的,一切工作正常,但如果不是,我不能重定向,瀏覽器只是掛起,最終超時。 我的理解是,瀏覽器不想重定向,因爲它正在等待上傳完成,但是我怎樣才能取消上傳,然後在我的js代碼中? 我可以解決這個問題,並寫入文件,然後刪除它,如果它不是正確的mimetype,但我認爲這樣做有點愚蠢,我寧願找到一種方法來觸發事件,將停止並立即重定向。 這裏是我的應用程序代碼(的片段):
app.get('/', function (req, res) {
res.render(__dirname + '/public/index.ejs', {error: 0});
});
app.get('/error', function (req, res) {
res.render(__dirname + '/public/index.ejs', {error: 1});
});
app.post('/upload', function (req, res) {
var timestamp = new Date().getTime().toString();
//console.log(timestamp);
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
if ("audio/wav" != mimetype)
{
console.log("invalid mimetype"); // that prints ok
// req.busboy.end(); // I tried that but it doesn't work
res.redirect('/error');
}
else
{
console.log("Uploading: " + mimetype);
fstream = fs.createWriteStream(__dirname + '/tmp/' + timestamp + filename);
file.pipe(fstream);
fstream.on('close', function() {
res.redirect('back');
});
}
});
});
任何人都可以點我在正確的方向? 謝謝你的幫助!
它爲我工作,我發佈我的解決方案,如果有人需要它http://stackoverflow.com/questions/30465882/node-busboy-abort-upload/32222839#32222839 – Michael