Znote (recipes)
  Get Znote  

Google Drive Upload

Upload files to Google Drive using OAuth2 authentication with Node.js.

 

Google Drive Upload

Prerequisites

  1. Enable the Google Drive APIGoogle Drive API Quickstart
  2. Create OAuth 2.0 credentials (Desktop App)Google Cloud Console – Credentials
  3. Download your OAuth client file, rename it to oauth2-drive.keys.json, and place it in your zenv folder.
open .

Install Dependencies

npm install -S googleapis@105 @google-cloud/local-auth@2.1.0

Upload a File to Google Drive

Run the following block once to authenticate and generate a token.json. This will persist your session using the refresh_token.

//exec: node
const path = require('path');
const fs = require('fs');
const { google } = require('googleapis');
const { authenticate } = require('@google-cloud/local-auth');

const CREDENTIALS_PATH = path.join(__dirname, 'oauth2-drive.keys.json');
const TOKEN_PATH = path.join(__dirname, 'token.json');
const FILE_PATH = path.join(__dirname, 'FILE_TO_UPLOAD.png');

const SCOPES = ['https://www.googleapis.com/auth/drive.file'];

async function loadSavedCredentialsIfExist() {
  try {
    const content = fs.readFileSync(TOKEN_PATH, 'utf8');
    const credentials = JSON.parse(content);
    return google.auth.fromJSON(credentials);
  } catch {
    return null;
  }
}

async function saveCredentials(auth) {
  const content = fs.readFileSync(CREDENTIALS_PATH, 'utf8');
  const keys = JSON.parse(content).installed;
  const payload = JSON.stringify({
    type: 'authorized_user',
    client_id: keys.client_id,
    client_secret: keys.client_secret,
    refresh_token: auth.credentials.refresh_token,
  });
  fs.writeFileSync(TOKEN_PATH, payload);
}

async function authorize() {
  let auth = await loadSavedCredentialsIfExist();
  if (!auth) {
    auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH });
    if (auth.credentials) await saveCredentials(auth);
  }
  return auth;
}

// Main logic
const auth = await authorize();
google.options({ auth });

const drive = google.drive({ version: 'v3', auth });

const response = await drive.files.create({
  requestBody: {
    name: 'FILE_TO_UPLOAD.png',
    mimeType: 'image/png',
  },
  media: {
    mimeType: 'image/png',
    body: fs.createReadStream(FILE_PATH),
  },
});

console.log('Uploaded file:', response.data);

// Example delete:
// await drive.files.delete({ fileId: 'your-file-id' });

Additional Resources

Related recipes