获取Google Drive NodeJS客户端的上传进度?

时间:2016-02-23 15:27:26

标签: node.js google-drive-api google-api-nodejs-client

我们从req = drive.files.insert获取请求对象后如何使用它找到文件上传进度?

我在req string中通过多次调用来搜索它,但无济于事。

function uploadFile(){
    var path = untildify("~/workspace/incomplete/aw.jpg");
    var drive = google.drive('v2');

    var req = drive.files.insert({
        resource: {
            title: 'aw.jpg'
        },
        media: {
            body: fs.createReadStream(path)
        },
        auth: oauth2Client
    }, function(err, response) {
        if (err)
            console.log(err);
        // else
        //  console.log(response);
    });

    console.log(req);
}

2 个答案:

答案 0 :(得分:2)

以下是它的完成方式

function uploadFile(){
    var path = untildify("~/workspace/a.jpg");
    var drive = google.drive('v2');
    console.log('start upload');
    var req = drive.files.insert({
        resource: {
            title: "a.jpg"
        },
        media: {
            body: fs.createReadStream(path)
        },
        auth: oauth2Client
    }, function(err, response, body) {
        if (err) {
            console.log(err);
        } else {
            console.log('finish upload');
            clearInterval(q);
        }
    });
    var q = setInterval(function () {
         console.log("Uploaded: " + req.req.connection.bytesWritten);
     }, 250);
}

参考:Node.js progress indicator feedback - 由Riel回答

特别感谢 Ryan Seys 帮助我。

答案 1 :(得分:0)

每次向API发出的请求都会返回request object,以便您跟踪请求的进度或有关请求的一般信息。您需要为收到的请求部分添加处理程序。

以下是示例代码:

part.addListener("request", function(received) {
    // Calculate upload progress
    var progress = (stream.bytesReceived / stream.bytesTotal * 100).toFixed(2);
    var mb = (stream.bytesTotal / 1024 / 1024).toFixed(1);

    sys.debug("Uploading " + mb + "mb (" + progress + "%)");

您可以在此blog找到相关文档。