Node Js Api Google Drive Upload File

Upload file to Google Drive with Node.js

Photo by Guido Klinge on Unsplash

Google Drive is a storage service available for Google users and allows yous to shop all kinds of files. All users have 15GB for complimentary after 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 bachelor to programmatically performs actions like Create a folder, add a file, search files, etc... It tin be useful in some cases:

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

Our goal

Here is the goal we want to attain: We have a .jpg file on our server, and nosotros want to upload it into our Google Drive inside a folder named Movie. If the folder doesn't exist, nosotros will create information technology, and finally, when the file is successfully updated, delete the file on the server.

Go API Credentials

The first step is to get our Google Drive credentials which are:

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

Yous demand to have a Google account for the steps below:

  1. Get to https://console.cloud.google.com/cloud-resource-director and click on the button "Create Project". Give a proper name to the project, click on "Create" to submit, and when for the creation to complete.
Create a new projection on Google Cloud Platform

2. Once the project is created, select it. Yous will 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 lot will be redirected to a page that lists all the Google APIs. Search for Google Drive API and click on it in the results list. On the adjacent page, click on the button "Enable", yous volition be redirected to a page when the API will be enabled.

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

Create OAuth Customer ID

5. On the new page, click on the button "CONFIGURE CONSENT SCREEN" then cheque "External" for the User Type. You can select "Internal" if the account yous employ is within an organization which is not my case. Click on the push button "Create"

Configure consent screen: select user type

On the new page, we accept a page with iv steps.

In step 1, give your application the proper noun and select your email address every bit the value for the input labeled "User back up electronic mail". Likewise, requite your email address every bit value for input labeled "Developer contact information". You can ignore other inputs since they aren't mandatory. Click on "Save and Continue"

Configure consent screen: Provide application data.

On step two, no change to do, and then click on "Save and Continue."
In step 3, add a Test user with your email address. Note that y'all can add together up to 100. Click on "Relieve and Go along"

Configure consent screen: Add together test users.

Stride 4 is simply a summary of the previous steps. Click on the push button "Back TO DASHBOARD."

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

Create OAuth client ID for a Web Application

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

At this step, we already take:

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

seven. Allow'due south get the refresh token.

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

Go Refresh Token

You will exist redirected to our Google Account to qualify the app to admission our Google Bulldoze.
Authorize, and you lot volition be redirected to a page with the content below:

Get Refresh Token: Exchange authorization code for tokens.

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

Refresh token generated successfully!

Projection structure

We have everything to start interact with Google Drive API. We will utilize the Node.js projection already set up upwardly with Typescript that we created throughout this previous tutorial so, clone the repository at this link then go within.

                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 binder, create a directory named "public" and copy a pic file inside, which will be uploaded to Google Drive. I took this picture show on Unsplash by SpaceX.

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

Setup environment variables

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

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

Create a file named .env 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 Bulldoze API credentials

Open src/alphabetize.ts and type the lawmaking beneath salvage and run the code yarn start to see the result:

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

Interact with Google Drive API

We volition create a file named googleDriveService which 4 methods:

  • createDriveClient(): create a client with the credentials generated before, and we will use it to make calls to Google Bulldoze API
  • searchFolder(): Search a folder within Google Bulldoze.
  • createFolder(): Create a new binder inside Google Drive
  • saveFile(): Create a new file in a folder within Google Drive
                import fs from 'fs'; // eslint-disable-next-line @typescript-eslint/no-var-requires const { google } = require('googleapis');  /**  * Browse the link beneath to see the complete object returned for folder/file creation and search  *  * @link https://developers.google.com/bulldoze/api/v3/reference/files#resource  */ type PartialDriveFile = {   id: string;   name: cord; };  type SearchResultResponse = {   kind: 'bulldoze#fileList';   nextPageToken: string;   incompleteSearch: boolean;   files: PartialDriveFile[]; };  export class GoogleDriveService {   private driveClient;    public constructor(clientId: string, clientSecret: cord, redirectUri: string, refreshToken: cord) {     this.driveClient = this.createDriveClient(clientId, clientSecret, redirectUri, refreshToken);   }    createDriveClient(clientId: string, clientSecret: string, redirectUri: cord, refreshToken: string) {     const client = new google.auth.OAuth2(clientId, clientSecret, redirectUri);      customer.setCredentials({ refresh_token: refreshToken });      render google.bulldoze({       version: 'v3',       auth: client,     });   }    createFolder(folderName: string): Promise<PartialDriveFile> {     return this.driveClient.files.create({       resources: {         proper name: folderName,         mimeType: 'awarding/vnd.google-apps.folder',       },       fields: 'id, name',     });   }    searchFolder(folderName: cord): Hope<PartialDriveFile | nix> {     return new Hope((resolve, reject) => {       this.driveClient.files.listing(         {           q: `mimeType='application/vnd.google-apps.binder' and proper noun='${folderName}'`,           fields: 'files(id, name)',         },         (err, res: { information: SearchResultResponse }) => {           if (err) {             render turn down(err);           }            return resolve(res.information.files ? res.data.files[0] : null);         },       );     });   }    saveFile(fileName: string, filePath: cord, fileMimeType: cord, 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

At present permit's use the GoogleDriveService in our index.ts file so replace the content by the one below:

                import dotenv from 'dotenv'; import * as 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 = 'Movie';    if (!fs.existsSync(finalPath)) {     throw new Error('File non found!');   }    let folder = await googleDriveService.searchFolder(folderName).take hold of((error) => {     console.error(error);     return nix;   });    if (!folder) {     folder = wait googleDriveService.createFolder(folderName);   }    wait googleDriveService.saveFile('SpaceX', finalPath, 'prototype/jpg', folder.id).take hold of((error) => {     panel.error(error);   });    console.info('File uploaded successfully!');    // Delete the file on the server   fs.unlinkSync(finalPath); })();              
Content of file src/index.ts

Type yarn start to beginning the application and see the outcome:

The film was uploaded to Google Drive successfully. 🎉

You can found the source code of this tutorial at this link.

I hope you find it helpful; follow me on Twitter for more content.

tejadawaithe.blogspot.com

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

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

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel