How to get progress status while uploading files to Google Drive using NodeJs?

血红的双手。 提交于 2019-12-24 18:50:25

问题


Im trying to get progress status values while uploading files to google Drive using nodeJs.

controller.js

exports.post = (req, res) => {
//file content is stored in req as a stream 
// 1qP5tGUFibPNaOxPpMbCQNbVzrDdAgBD is the folder ID (in google drive) 
  googleDrive.makeFile("file.txt","1qP5tGUFibPNaOxPpMbCQNbVzrDdAgBD",req);

};

googleDrive.js

...
    makeFile: function (fileName, root,req) {

        var fileMetadata = {
            'name': fileName,
            'mimeType': 'text/plain',
            'parents': [root]
        };

        var media = {
            mimeType: 'text/plain',
            body: req
        };

        var r = drive.files.create({
            auth: jwToken,
            resource: fileMetadata,
            media: media,
            fields: 'id'
        }, function (err, file) {
            if (err) {
                // Handle error
                console.error(err);
            } else {
                // r => undefined
                console.log("Uploaded: " + r);
            }
        });


    },
...

i followed this link but got always an undefined value


回答1:


How about this modification?

Modification point:

  • It used onUploadProgress.

Modified script:

makeFile: function (fileName, root,req) {
    var fileMetadata = {
        'name': fileName,
        'mimeType': 'text/plain',
        'parents': [root]
    };

    var media = {
        mimeType: 'text/plain',
        body: req
    };

    var r = drive.files.create({
        auth: jwToken,
        resource: fileMetadata,
        media: media,
        fields: 'id'
    }, {
      onUploadProgress: function(e) {
        process.stdout.clearLine();
        process.stdout.cursorTo(0);
        process.stdout.write(e.bytesRead.toString());
      },
    }, function (err, file) {
        if (err) {
            // Handle error
            console.error(err);
        } else {
            console.log("Uploaded: " + file.data.id);
        }
    });
},

Note:

  • If you want to show the progression as "%", please use the file size.
  • It was confirmed that this script worked at googleapis@33.0.0.

References:

  • axios
  • test of google/google-api-nodejs-client

In my environment, I'm using the script like above. But if this didn't work in your environment and if I misunderstand your question, I'm sorry.



来源:https://stackoverflow.com/questions/52026500/how-to-get-progress-status-while-uploading-files-to-google-drive-using-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!