Node Js Google Drive Api Upload Id

Upload file to Google Drive with Node.js

Photo by Guido Klinge on Unsplash

Google Bulldoze is a storage service available for Google users and allows you to store all kinds of files. All users have 15GB for free later created their Google account, and all you demand to do is log in at https://drive.google.com and then upload your files inside. For advanced users (developers), there is an API available to programmatically performs actions like Create a binder, add a file, search files, etc... It can be useful in some cases:

  • Backup your database and upload it to your drive
  • Set a Cron job to look upward inside a folder and upload the files inside
  • Receive an email when you reach the storage threshold
  • Delete all files older than a specific date

Our goal

Hither is the goal we want to accomplish: We have a .jpg file on our server, and we want to upload it into our Google Drive within a folder named Pic. If the folder doesn't exist, we will create it, and finally, when the file is successfully updated, delete the file on the server.

Get API Credentials

The first footstep is to go our Google Drive credentials which are:

  • A Customer Id and a Customer Secret
  • A redirect URI and refresh token

You lot demand to have a Google account for the steps beneath:

  1. Go to https://console.deject.google.com/cloud-resource-managing director and click on the button "Create Project". Requite a name to the project, click on "Create" to submit, and when for the cosmos to complete.
Create a new project on Google Cloud Platform

2. One time the project is created, select it. Y'all volition be redirected to the console dashboard. On the sidebar card, click on the menu "APIs & Services".
Locate the button labeled "ENABLE APIS AND SERVICES" and click on it.

Enable APIs & Services on Google Cloud Platform

iii. You will exist redirected to a folio that lists all the Google APIs. Search for Google Bulldoze API and click on it in the results listing. On the adjacent folio, click on the button "Enable", you will be redirected to a folio when the API will be enabled.

4. On the new page, click on the carte in the sidebar labeled "Credentials". On the next folio, locate the driblet-down button labeled "CREATE CREDENTIALS" click on it and select the drop-down menu labeled "OAuth client ID"

Create OAuth Client ID

5. On the new folio, click on the button "CONFIGURE CONSENT SCREEN" and so check "External" for the User Type. You tin can select "Internal" if the account y'all use is inside an organization which is not my case. Click on the push button "Create"

Configure consent screen: select user type

On the new folio, nosotros have a page with four steps.

In stride i, give your application the name and select your email address as the value for the input labeled "User back up email". Also, give your email address every bit value for input labeled "Developer contact information". You tin can ignore other inputs since they aren't mandatory. Click on "Relieve and Go along"

Configure consent screen: Provide application data.

On pace 2, no change to practice, so click on "Relieve and Go on."
In footstep iii, add a Test user with your email address. Annotation that y'all can add upwards to 100. Click on "Save and Continue"

Configure consent screen: Add test users.

Step four is but a summary of the previous steps. Click on the button "Dorsum TO DASHBOARD."

six. On the new page, click on the menu in the sidebar labeled "Credentials". On the next page, locate the drop-downwardly push button labeled "CREATE CREDENTIALS" click on it and select the driblet-down menu labeled "OAuth client ID"
On the next page, select "Web Application" every bit the value of the input labeled "Awarding type,"
Requite a proper noun to our Web Application.
In the section "Authorized redirect URIs," click on "ADD URI" and fill the input with this value: https://developers.google.com/oauthplayground

Create OAuth customer ID for a Spider web Application

Click on "CREATE" to submit, and hooray 🎉 , we take our Client ID and Customer Secret.

At this pace, we already have:

  • Customer ID ✅
  • Client Secret ✅
  • Redirect URI ✅ (https://developers.google.com/oauthplayground)
  • Refresh Token ❌

7. Permit'southward get the refresh token.

Go to https://developers.google.com/oauthplayground

Get Refresh Token

You lot volition exist redirected to our Google Account to authorize the app to access our Google Drive.
Authorize, and you volition be redirected to a folio with the content below:

Get Refresh Token: Substitution authorisation lawmaking for tokens.

When the request is completed, you will accept your refresh token 🎉.

Refresh token generated successfully!

Projection structure

We have everything to showtime interact with Google Drive API. We will employ the Node.js project already set upward with Typescript that we created throughout this previous tutorial then, clone the repository at this link then go inside.

                git clone https://github.com/tericcabrel/node-ts-starter.git node-gdrive-api  cd node-gdrive-api                              
Clone repository containing the minimal setup

At the root folder, create a directory named "public" and copy a picture file inside, which will be uploaded to Google Bulldoze. I took this motion-picture show on Unsplash past SpaceX.

                ├── public │   ├── spacex-uj3hvdfQujI-unsplash.jpg ├── src │   ├── index.ts ├── .eslintrc.js ├── .prettierrc.js ├── README.md ├── package.json ├── tsconfig.json └── yarn.lock              
Directory construction

Setup environs variables

We need the credentials nosotros created previously to interact with Google Drive API and to avoid using them in raw, we need to load them from a configuration file. We volition use the dotenv package; we also need the Node.js SDK for Google API. So, inside the final at the project root, run the code below to install them:

                yarn install yarn add dotenv googleapis yarn add -D @types/node              
Install dotenv and googleapis

Create a file named .env and then add the content below:

                GOOGLE_DRIVE_CLIENT_ID=<YOUR_CLIENT_ID> GOOGLE_DRIVE_CLIENT_SECRET=<YOUR_CLIENT_SECRET> GOOGLE_DRIVE_REDIRECT_URI=https://developers.google.com/oauthplayground GOOGLE_DRIVE_REFRESH_TOKEN=<YOUR_REFRESH_TOKEN>              
Configuration files with Google Drive API credentials

Open src/index.ts and type the code below salvage and run the code yarn start to see the result:

                import dotenv from 'dotenv';  dotenv.config();  console.log(procedure.env.GOOGLE_DRIVE_CLIENT_ID); console.log(process.env.GOOGLE_DRIVE_CLIENT_SECRET); console.log(process.env.GOOGLE_DRIVE_REDIRECT_URI); panel.log(process.env.GOOGLE_DRIVE_REFRESH_TOKEN);              
Content of src/index.ts

Interact with Google Drive API

We will create a file named googleDriveService which 4 methods:

  • createDriveClient(): create a client with the credentials generated before, and we volition use it to brand calls to Google Drive API
  • searchFolder(): Search a folder within Google Drive.
  • createFolder(): Create a new folder within Google Drive
  • saveFile(): Create a new file in a binder within Google Drive
                import fs from 'fs'; // eslint-disable-adjacent-line @typescript-eslint/no-var-requires const { google } = require('googleapis');  /**  * Browse the link below to see the complete object returned for binder/file creation and search  *  * @link https://developers.google.com/drive/api/v3/reference/files#resource  */ type PartialDriveFile = {   id: string;   proper name: cord; };  type SearchResultResponse = {   kind: 'drive#fileList';   nextPageToken: string;   incompleteSearch: boolean;   files: PartialDriveFile[]; };  consign grade GoogleDriveService {   individual driveClient;    public constructor(clientId: string, clientSecret: string, redirectUri: cord, refreshToken: cord) {     this.driveClient = this.createDriveClient(clientId, clientSecret, redirectUri, refreshToken);   }    createDriveClient(clientId: cord, clientSecret: cord, redirectUri: string, refreshToken: string) {     const client = new google.auth.OAuth2(clientId, clientSecret, redirectUri);      client.setCredentials({ refresh_token: refreshToken });      return google.drive({       version: 'v3',       auth: customer,     });   }    createFolder(folderName: string): Promise<PartialDriveFile> {     return this.driveClient.files.create({       resource: {         name: folderName,         mimeType: 'application/vnd.google-apps.folder',       },       fields: 'id, proper noun',     });   }    searchFolder(folderName: string): Promise<PartialDriveFile | null> {     return new Promise((resolve, reject) => {       this.driveClient.files.list(         {           q: `mimeType='application/vnd.google-apps.binder' and name='${folderName}'`,           fields: 'files(id, proper name)',         },         (err, res: { data: SearchResultResponse }) => {           if (err) {             return reject(err);           }            return resolve(res.data.files ? res.data.files[0] : null);         },       );     });   }    saveFile(fileName: string, filePath: string, fileMimeType: string, folderId?: string) {     return this.driveClient.files.create({       requestBody: {         name: fileName,         mimeType: fileMimeType,         parents: folderId ? [folderId] : [],       },       media: {         mimeType: fileMimeType,         torso: fs.createReadStream(filePath),       },     });   } }              
Content of file src/googleDriveService.ts

Now permit's use the GoogleDriveService in our index.ts file so supersede the content by the one beneath:

                import dotenv from 'dotenv'; import * equally path from 'path'; import * every bit fs from 'fs';  import { GoogleDriveService } from './googleDriveService';  dotenv.config();  const driveClientId = process.env.GOOGLE_DRIVE_CLIENT_ID || ''; const driveClientSecret = process.env.GOOGLE_DRIVE_CLIENT_SECRET || ''; const driveRedirectUri = process.env.GOOGLE_DRIVE_REDIRECT_URI || ''; const driveRefreshToken = process.env.GOOGLE_DRIVE_REFRESH_TOKEN || '';  (async () => {   const googleDriveService = new GoogleDriveService(driveClientId, driveClientSecret, driveRedirectUri, driveRefreshToken);    const finalPath = path.resolve(__dirname, '../public/spacex-uj3hvdfQujI-unsplash.jpg');   const folderName = 'Picture';    if (!fs.existsSync(finalPath)) {     throw new Error('File not constitute!');   }    let folder = look googleDriveService.searchFolder(folderName).grab((mistake) => {     console.mistake(error);     return null;   });    if (!folder) {     binder = await googleDriveService.createFolder(folderName);   }    await googleDriveService.saveFile('SpaceX', finalPath, 'image/jpg', folder.id).catch((error) => {     console.error(error);   });    console.info('File uploaded successfully!');    // Delete the file on the server   fs.unlinkSync(finalPath); })();              
Content of file src/index.ts

Type yarn outset to outset the awarding and see the upshot:

The picture was uploaded to Google Drive successfully. 🎉

Yous can constitute the source code of this tutorial at this link.

I promise y'all find it helpful; follow me on Twitter for more than content.

johnstonyetrome.blogspot.com

Source: https://blog.tericcabrel.com/upload-file-to-google-drive-with-nodejs/

0 Response to "Node Js Google Drive Api Upload Id"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel