如何循环多方文件上传?

时间:2015-12-26 21:35:03

标签: node.js azure http-post azure-storage-blobs multipart

我正在为客户构建网站,他们需要将多个文件(这很重要)上传到Azure Blob存储容器。我目前使用此代码:

app.post("/upload", function (req, res) {
     var blobService = azure.createBlobService("mainwebsite", "XXX");
     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("images", name, part, size, function(error) {
                res.send({ success: "Your file(s) have been uploaded successfully."});
            });
        } else {
            return;
        }
    });
    form.parse(req);
});

我需要更改此代码,以便枚举传递给POST请求的所有文件。有人可以请我为此透露一下吗?

1 个答案:

答案 0 :(得分:1)

您可以使用功能createWriteStreamToBlockBlob(),它会将writeStream然后pipe部分返回writeStream,这里是代码段:

router.get('/multipart', function (req, res){
    res.send(
        '<form action="/test/multipart" enctype="multipart/form-data" method="post">' +
        '<input type="file" name="upload[]" multip le="multiple"><br>' +
        '<input type="file" name="upload[]" multiple="multiple"><br>' +
        '<input type="submit" value="Upload">' +
        '</form>'
    )
})
router.post('/multipart', function (req, res) {
    var form = new multiparty.Form({});
    var files = [];
    var finished = [];
    form.on("part", function (part) {
        if (part.filename) {
            var size = part.byteCount - part.byteOffset;
            var name = part.filename;
            var out = blobsrv.createWriteStreamToBlockBlob("images", name);
            out.on("finish", function () {
                console.log("finish upload file: " + name);
                finished.push(name);
                if (finished.length == files.length) {
                    res.send(JSON.stringify(finished))
                }
            })
            part.on('end', function () {
                console.log('part end')
                files.push(name);
            })
            part.pipe(out)
        } else {
            return;
        }
    });

    form.parse(req);
})