且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Node 将上传的文件流式传输到 Azure blob 存储

更新时间:2023-02-09 09:31:15

解决方案(基于与@danielepolencic 的讨论)

SOLUTION (based on discussion with @danielepolencic)

使用 Multiparty(npm install multiparty),Formidable 的一个分支,如果我们从 Express 禁用 bodyparser() 中间件,我们可以访问多部分数据(更多信息请参阅他们的注释).与 Formidable 不同,Multiparty 不会将文件流式传输到磁盘,除非您告诉它.

Using Multiparty(npm install multiparty), a fork of Formidable, we can access the multipart data if we disable the bodyparser() middleware from Express (see their notes on doing this for more information). Unlike Formidable, Multiparty will not stream the file to disk unless you tell it to.

app.post('/upload', function (req, res) {
    var blobService = azure.createBlobService();
    var form = new multiparty.Form();
    form.on('part', function(part) {
        if (part.filename) {

            var size = part.byteCount - part.byteOffset;
            var name = part.filename;

            blobService.createBlockBlobFromStream('c', name, part, size, function(error) {
                if (error) {
                    res.send({ Grrr: error });
                }
            });
        } else {
            form.handlePart(part);
        }
    });
    form.parse(req);
    res.send('OK');
});

感谢@danielepolencic 帮助找到解决方案.

Props to @danielepolencic for helping to find the solution to this.