如何将图像从 NodeJS API 上传到谷歌驱动器

Kir*_*ddy 10 javascript google-api node.js google-drive-api

我已经编写了 API 并且必须上传到 Heroku 服务器。当我在更改后在 Heroku 中推送数据时,所有图像都消失了。我不知道为什么他们没有显示。我发现了一些其他选项,例如直接在 Google Drive 中上传图片,并且我已经浏览了相关文档。我找不到任何与此相关的资源。

任何人都可以帮助我提供将文件上传到 Google Drive 的参考或建议吗?

Kee*_*asa 11

@KarlR 的回答很有帮助,但代码有其自身的缺陷。(范围不支持文件上传)。让我一步一步地解释这一点,以便您可以轻松地将文件上传到 Google 云端硬盘。

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

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

第 2 步:命名函数uploadFile并更改范围以适合上传。代码段如下。

在下面的示例中,文件是从Google Drive的文件夹中提取并重files/photo.jpg命名为photo.jpg并上传到该root文件夹中的。

const fs = require('fs');
const readline = require('readline');
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);
});
Run Code Online (Sandbox Code Playgroud)

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

uploadFile函数中,更改name属性。

const fileMetadata = {
        'name': 'any_name_you_like'
};
Run Code Online (Sandbox Code Playgroud)

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

您只需更改uploadFile函数中的以下代码段。查看最常用的 MIME 类型作为您首选的文件扩展名。

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

第 5 步:将文件上传到 Google Drive 上的特定文件夹

打开浏览器并登录到您的 Google Drive。转到特定文件夹并查看浏览器 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']
};
Run Code Online (Sandbox Code Playgroud)

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