Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

Upload file to google drive using REST API in Node.js

I am trying to upload a file to google drive using rest API(insert) in node.js, I have access_token and refresh_token. how can I upload without any sdk.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I was successful in testing this NodeJS upload by modifying the NodeJS basic upload sample a bit and mixing it with the already available NodeJS Quickstart

Here's the upload function:

function uploadFile(auth){
  var drive = google.drive('v3');
  var fileMetadata = {
         'name': 'uploadImageTest.jpeg'
      };
  var media = {
          mimeType: 'image/jpeg',
          //PATH OF THE FILE FROM YOUR COMPUTER
          body: fs.createReadStream('/usr/local/google/home/rrenacia/Downloads/noogui.jpeg')
      };

      drive.files.create({
          auth: auth,
          resource: fileMetadata,
          media: media,
          fields: 'id'
      }, function (err, file) {
      if (err) {
          // Handle error
          console.error(err);
      } else {
          console.log('File Id: ', file.id);
      }
   });
}

You can use the NodeJS Quickstart as reference for authorization. Change listFiles function name:

authorize(JSON.parse(content), listFiles);

to the name of your upload function, in this case:

authorize(JSON.parse(content), uploadFile);

A sucessful upload on my Google drive:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...