如何使用Node.js Rest API将文件上传到Google云端硬盘?

时间:2019-04-24 08:29:50

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

我必须使用Angular作为前端并将Node.js Rest API作为后端将文档上传到Google Drive。对于上传文件,我需要身份验证。但是我不知道如何处理认证。我可以使用sample从Node.js直接上载。考虑到auth,如何将该node.js用作后端?我需要建议或示例。

这是我用于上传文件的代码:

 "use strict";
 const fs = require("fs");
 const readline = require("readline");
 const { google } = require("googleapis");
 const sampleClient = require("./sampleclient");

 const drive = google.drive({
 version: "v3",
 auth: sampleClient.oAuth2Client
 });
 async function runSample(fileName) {
 const fileSize = fs.statSync(fileName).size;
 const res = await drive.files.create(
 {
  requestBody: {
        mimeType: 'application/vnd.google-apps.document',
        name: fileName
  },
   fields: "*",
  media: {
    body: fs.createReadStream(fileName),
    mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.presentation"
  }
},
{
  onUploadProgress: evt => {
    const progress = (evt.bytesRead / fileSize) * 100;
    readline.clearLine();
    readline.cursorTo(0);
    process.stdout.write(`${Math.round(progress)}% complete`);
  }
}
);
return res.data;
}
  if (module === require.main) {
const fileName = process.argv[2];
const scopes = ["https://www.googleapis.com/auth/drive"];
sampleClient
.authenticate(scopes)
.then(() => runSample(fileName))
.catch(console.error);
}

module.exports = {
runSample,
client: sampleClient.oAuth2Client
};

我的表情:

  1. Upload file to Google Drive from URL using REST API
  2. Upload file to google drive using REST API in Node.js
  3. How do I authorise an app (web or installed) without user intervention?

但是还是不明白。我需要清楚地理解。

谢谢。

0 个答案:

没有答案