2017-10-18 75 views
2

有沒有一種方式,使用表達路由使用者可以發送輸入流到端點並閱讀它?nodejs輸入流使用快遞

總之,我希望端點用戶通過流式傳輸來上傳文件,而不是使用多部分/表單方式。例如:

app.post('/videos/upload', (request, response) => { 
    const stream = request.getInputStream(); 
    const file = stream.read(); 
    stream.on('done', (file) => { 
     //do something with the file 
    }); 
}); 

是否可以這樣做?

+0

圖書館https://github.com/mscdex/busboy將做到這一點,你也得到每個文件流。 –

回答

3

在快遞,request對象是http.IncomingMessage的增強版本,其「......實現了可讀流接口」

換句話說,request已經流:

app.post('/videos/upload', (request, response) => { 
    request.on('data', data => { 
    ...do something... 
    }).on('close',() => { 
    ...do something else... 
    }); 
}); 

如果你的意圖是首先將整個文件讀入內存(可能不是),你也可以使用bodyParser.raw()

const bodyParser = require('body-parser'); 
... 
app.post('/videos/upload', bodyParser.raw({ type : '*/*' }), (request, response) => { 
    let data = req.body; // a `Buffer` containing the entire uploaded data 
    ...do something... 
});