Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Google Drive API无法将文件上载到特定文件夹_Node.js_File Upload_Google Api_Google Drive Api_Share - Fatal编程技术网

Node.js Google Drive API无法将文件上载到特定文件夹

Node.js Google Drive API无法将文件上载到特定文件夹,node.js,file-upload,google-api,google-drive-api,share,Node.js,File Upload,Google Api,Google Drive Api,Share,我有一个无限存储的谷歌驱动器帐户从我的学校帐户,所以我与我的主谷歌帐户共享驱动器,我想使用谷歌驱动器的API上传视频到共享驱动器的文件输入形式。这是我要存储文件的位置: 我使用express,googleapis,multer 我就是这样做的: 这是我的凭证。json: { "web": { "client_id": "607849031009-4gsgo99bbskgsou5676b59ievp4fadmb.apps.google

我有一个无限存储的谷歌驱动器帐户从我的学校帐户,所以我与我的主谷歌帐户共享驱动器,我想使用谷歌驱动器的API上传视频到共享驱动器的文件输入形式。这是我要存储文件的位置:

我使用
express
googleapis
multer

我就是这样做的:

这是我的
凭证。json

{
  "web": {
    "client_id": "607849031009-4gsgo99bbskgsou5676b59ievp4fadmb.apps.googleusercontent.com",
    "project_id": "spiritual-aloe-296616",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "OOAA7s1zXEUZ-5KemIhzjt4G",
    "redirect_uris": ["http://localhost:5000/google/callback"],
    "javascript_origins": ["http://localhost:5000"]
  }
}
我使用
express
写入服务器,并使用multer将文件上载到服务器:

const fs = require('fs');
const express = require('express');
const multer = require('multer');
const OAuth2Data = require('./credentials.json');
var name, pic;

const {google} = require('googleapis');

const app = express();

const CLIENT_ID = OAuth2Data.web.client_id;
const CLIENT_SECRET = OAuth2Data.web.client_secret;
const REDIRECT_URL = OAuth2Data.web.redirect_uris[0];

const oAuth2Client = new google.auth.OAuth2(
  CLIENT_ID,
  CLIENT_SECRET,
  REDIRECT_URL
);
var authed = false;

// If modifying these scopes, delete token.json.
const SCOPES =
  'https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/userinfo.profile';

app.set('view engine', 'ejs');

var Storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './images');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '_' + Date.now() + '_' + file.originalname);
  },
});

var upload = multer({
  storage: Storage,
}).single('file'); //Field name and max count

app.get('/', (req, res) => {
  if (!authed) {
    // Generate an OAuth URL and redirect there
    var url = oAuth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: SCOPES,
    });
    console.log(url);
    res.render('index', {url: url});
  } else {
    var oauth2 = google.oauth2({
      auth: oAuth2Client,
      version: 'v2',
    });
    oauth2.userinfo.get(function (err, response) {
      if (err) {
        console.log(err);
      } else {
        console.log(response.data);

        res.render('success', {
          success: false,
        });
      }
    });
  }
});

app.post('/upload', (req, res) => {
  upload(req, res, function (err) {
    if (err) {
      console.log(err);
      return res.end('Something went wrong');
    } else {
      console.log(req.file.path);
      const drive = google.drive({version: 'v3', auth: oAuth2Client});
      const fileMetadata = {
        name: req.file.filename,
      };
      const media = {
        mimeType: req.file.mimetype,
        body: fs.createReadStream(req.file.path),
      };
      drive.files.create(
        {
          resource: fileMetadata,
          media: media,
          fields: 'id',
        },
        (err, file) => {
          if (err) {
            // Handle error
            console.error(err);
          } else {
            fs.unlinkSync(req.file.path);
            res.render('success', {name: name, pic: pic, success: true});
          }
        }
      );
    }
  });
});

app.get('/logout', (req, res) => {
  authed = false;
  res.redirect('/');
});

app.get('/google/callback', function (req, res) {
  const code = req.query.code;
  if (code) {
    // Get an access token based on our OAuth code
    oAuth2Client.getToken(code, function (err, tokens) {
      if (err) {
        console.log('Error authenticating');
        console.log(err);
      } else {
        console.log('Successfully authenticated');
        console.log(tokens);
        oAuth2Client.setCredentials(tokens);

        authed = true;
        res.redirect('/');
      }
    });
  }
});

app.listen(5000, () => {
  console.log('App is listening on Port 5000');
});
最后它成功了,但问题是,它上传到了我的谷歌硬盘账户主页

同时,我想把它保存在共享驱动器文件夹中,抱歉我的英语不好,谢谢你帮助我,希望你有一个美好的一天和祝福的感恩节:)

更新

这是共享驱动器的url:
https://drive.google.com/drive/u/3/folders/0AKRMoXHA-b-NUk9PVA?fbclid=IwAR2je0Ip7xwsaX7ghqZ0F0JWYYjImyvG1BEnRK2DjCGvRKFg7THFX8


还有一件事是,我如何获得我刚刚上传的文件的url?

您可以通过在请求正文中添加“parents”属性在特定文件夹中创建文件,并根据文件夹的id设置其值

示例:

folder_id = 'xxxxxxxxsamplefolderidxxxx'
file_metadata = {
'name': 'photo.jpg',
'parents': [folder_id]
}
在代码中:

const fileMetadata = {
    name: req.file.filename,
    parents: 'xxxxxxxxsamplefolderidxxxx'
  };
另外,如果在创建请求中未指定“父项”,则文件将直接放置在用户的“我的驱动器”文件夹中。如果未指定为复制请求的一部分,则该文件将继承源文件的任何可发现父级。更新请求必须使用addParents和removeParents参数来修改父列表

参考:

要获取文件夹id,可以从drives.google.com中的文件夹链接获取

示例:

folder_id = 'xxxxxxxxsamplefolderidxxxx'
file_metadata = {
'name': 'photo.jpg',
'parents': [folder_id]
}

其中文件夹Id=1234SampleFolderId

(根据其他问题更新)

注意: 文件夹Id应在“folders/”之后开始,并在“?”之前结束

例如: 文件夹/此处是文件夹ID?fbclid=

关于上载的文件的url,成功创建文件将在响应正文中返回文件资源

文件资源引用:

webContentLink -用于在浏览器中下载文件内容的链接

webViewLink
-用于在相关的谷歌编辑器或浏览器查看器中打开文件的链接。

非常感谢您的帮助,我只是更新问题以让您看到url,我得到了家长的概念,但在
/folders/xxxx
之前,它得到了前缀,那么我该如何处理它?我该如何获取刚刚上传的文件的url?folderId应该在“folders/”之后和“?”之前开始?例如:folders/xxxHereIsTheFolderId?fbclid=关于上传的文件的url。成功创建文件将在响应正文中返回文件资源。文件资源参考:WebContent链接-用于在浏览器中下载文件内容的链接。webViewLink-用于在浏览器中的相关Google编辑器或查看器中打开文件的链接。我对其进行了更新投票,那么/folders/xxx之前的前缀/u/3如何处理?