Get upload progress for Google Drive NodeJS client

2019-02-15 21:33发布

问题:

After we get the request object from req = drive.files.insert how to use it find file upload progress ?

I searched for it in the req string by calling it multiple times but to no avail.

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);
}

回答1:

Here's how it's done

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);
}

Reference : Node.js progress indicator feedback - Answer by Riel

And special thanks to Ryan Seys for helping me out.



回答2:

Every request to the API returns a request object, allowing you to track the request's progress or general information about the request. You need to add a handler for a request part received.

Here is the sample code:

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 + "%)");

You can find the documentation in this blog.