如何从Node.js API将图像上传到Google驱动器

时间:2018-08-16 05:55:50

标签: javascript node.js reactjs express google-drive-team-drive

我编写了API并在更改后将数据推送到Heroku中时将其上传到Heroku服务器中,然后所有图像都消失了。我不知道为什么他们没有出现。我找到了其他一些选项,例如直接在Google驱动器中上传图片,我们可以在那里获取,但是我已经浏览了所有文档。我还没有做到谷歌驱动器的图像 谁能帮助我提出任何推荐或建议等? 谢谢副词

2 个答案:

答案 0 :(得分:1)

如果您想使用npm软件包将图像上传到Google云端硬盘,则可以尝试以下方法:

  • 转到该站点:Turn on Google Drive API,创建凭据.json文件,下载并移至工作目录。
  • 添加googleapis程序包:yarn add googleapis
  • 创建两个函数:authorizeuploadFile
  • credentials.json文件中读取您的凭据,调用authorize并调用uploadFile作为回调。

上传图片的代码:

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

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];
const TOKEN_PATH = 'token.json';

/**
 * Create an OAuth2 client with the given credentials, and then execute the given callback function.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}
/**
* Describe with given media and metaData and upload it using google.drive.create method()
*/ 
function uploadFile(auth) {
  const drive = google.drive({version: 'v3', auth});
  const fileMetadata = {
    'name': 'photo.jpg'
  };
  const media = {
    mimeType: 'image/jpeg',
    body: fs.createReadStream('files/photo.jpg')
  };
  drive.files.create({
    resource: fileMetadata,
    media: media,
    fields: 'id'
  }, (err, file) => {
    if (err) {
      // Handle error
      console.error(err);
    } else {
      console.log('File Id: ', file.id);
    }
  });
}

fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Drive API.
  authorize(JSON.parse(content), uploadFile);
});

还要检查官方文档:Node.js quickstartUploading files

答案 1 :(得分:-1)

@KarlR的回答很有帮助,但是代码本身有错误。 (该范围不支持文件上传)。让我逐步说明这一点,以便您可以轻松地将文件上传到Google云端硬盘。

步骤1:转到Google Drive API V3 NodeJS快速入门

按照初始步骤进行操作,看看它是否有效。然后继续下一步。

步骤2:具有一个名为uploadFile的函数,并更改范围以适合上载。代码段如下所示。

在下面的示例中,该文件是从files/photo.jpg获取的,并被重命名为photo.jpg并上传到Google云端硬盘的root文件夹中。

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

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

/**
 * Create an OAuth2 client with the given credentials, and then execute the given callback function.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getAccessToken(oAuth2Client, callback) {
    const authUrl = oAuth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES,
    });
    console.log('Authorize this app by visiting this url:', authUrl);
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    rl.question('Enter the code from that page here: ', (code) => {
        rl.close();
        oAuth2Client.getToken(code, (err, token) => {
            if (err) return console.error('Error retrieving access token', err);
            oAuth2Client.setCredentials(token);
            // Store the token to disk for later program executions
            fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
                if (err) return console.error(err);
                console.log('Token stored to', TOKEN_PATH);
            });
            callback(oAuth2Client);
        });
    });
}
/**
* Describe with given media and metaData and upload it using google.drive.create method()
*/ 
function uploadFile(auth) {
  const drive = google.drive({version: 'v3', auth});
  const fileMetadata = {
    'name': 'photo.jpg'
  };
  const media = {
    mimeType: 'image/jpeg',
    body: fs.createReadStream('files/photo.jpg')
  };
  drive.files.create({
    resource: fileMetadata,
    media: media,
    fields: 'id'
  }, (err, file) => {
    if (err) {
      // Handle error
      console.error(err);
    } else {
      console.log('File Id: ', file.id);
    }
  });
}

fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Drive API.
  authorize(JSON.parse(content), uploadFile);
});

第3步:更改要上传的文件的名称

uploadFile功能中,更改name属性。

const fileMetadata = {
        'name': 'any_name_you_like'
};

第4步:上传不同的文件类型

您只需要在uploadFile函数中更改以下代码段。有关首选的文件扩展名,请参见mostly used mime types

const media = {
     mimeType: 'any_mime_type',
     body: fs.createReadStream('files/photo.jpg')
};

第5步:将文件上传到Google云端硬盘上的特定文件夹

打开浏览器并登录到您的Google云端硬盘。转到特定文件夹,然后查看浏览器URL。如下图所示。

https://drive.google.com/drive/u/0/folders/1xxxXj_sdsdsdsd0Rw6qDf0jLukG6eEUl

1xxxXj_sdsdsdsd0Rw6qDf0jLukG6eEUl 是文件夹ID(父ID)。在uploadFile函数中更改以下代码段。

const fileMetadata = {
        'name': 'any_file_name',
        parents: ['1xxxXj_sdsdsdsd0Rw6qDf0jLukG6eEUl']
};

希望这足以满足您的要求。