How to See Google Drive Api Upload File

Upload file to Google Drive with Node.js

Photo by Guido Klinge on Unsplash

Google Drive is a storage service bachelor for Google users and allows you to shop all kinds of files. All users have 15GB for free afterwards created their Google account, and all you lot need to do is log in at https://drive.google.com then upload your files inside. For advanced users (developers), there is an API available to programmatically performs deportment 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 bulldoze
  • Set up a Cron chore to look up within a folder and upload the files inside
  • Receive an email when you reach the storage threshold
  • Delete all files older than a specific appointment

Our goal

Here is the goal we desire to achieve: We have a .jpg file on our server, and we want to upload it into our Google Drive inside a binder named Film. If the folder doesn't exist, nosotros volition create it, and finally, when the file is successfully updated, delete the file on the server.

Become 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

You need to have a Google account for the steps below:

  1. Go to https://console.cloud.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 creation to consummate.
Create a new project on Google Deject Platform

two. Once the projection is created, select information technology. You will be redirected to the console dashboard. On the sidebar menu, click on the carte "APIs & Services".
Locate the button labeled "ENABLE APIS AND SERVICES" and click on it.

Enable APIs & Services on Google Cloud Platform

3. You volition exist 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", you will exist redirected to a page when the API will be enabled.

4. On the new page, click on the carte du jour in the sidebar labeled "Credentials". On the next folio, locate the drib-downwardly push labeled "CREATE CREDENTIALS" click on information technology and select the drop-down card labeled "OAuth client ID"

Create OAuth Client ID

5. On the new page, click on the button "CONFIGURE CONSENT SCREEN" then check "External" for the User Type. Yous can select "Internal" if the account you use is inside an organization which is non my case. Click on the button "Create"

Configure consent screen: select user blazon

On the new folio, we accept a page with 4 steps.

In step ane, give your application the proper noun and select your email address as the value for the input labeled "User support electronic mail". As well, give your email address as value for input labeled "Programmer contact information". You can ignore other inputs since they aren't mandatory. Click on "Save and Keep"

Configure consent screen: Provide application information.

On step 2, no modify to practice, so click on "Save and Continue."
In pace 3, add a Exam user with your electronic mail address. Note that y'all tin add upwardly to 100. Click on "Salve and Continue"

Configure consent screen: Add test users.

Footstep 4 is just a summary of the previous steps. Click on the button "BACK TO DASHBOARD."

vi. On the new page, click on the carte du jour in the sidebar labeled "Credentials". On the next folio, locate the drop-down button labeled "CREATE CREDENTIALS" click on information technology and select the drop-down menu labeled "OAuth client ID"
On the next page, select "Web Application" every bit the value of the input labeled "Awarding type,"
Give a proper name to our Web Application.
In the department "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 Awarding

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

At this step, we already have:

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

vii. Let's become the refresh token.

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

Get Refresh Token

Y'all will exist redirected to our Google Business relationship to authorize the app to access our Google Drive.
Authorize, and you will be redirected to a page with the content beneath:

Get Refresh Token: Exchange authorization lawmaking for tokens.

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

Refresh token generated successfully!

Project structure

Nosotros take everything to start interact with Google Drive API. We volition use the Node.js project already set up up with Typescript that we created throughout this previous tutorial and so, clone the repository at this link and so 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 flick file within, which volition exist uploaded to Google Drive. I took this picture on Unsplash by SpaceX.

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

Setup environment variables

We demand the credentials nosotros created previously to collaborate with Google Drive API and to avert using them in raw, we demand to load them from a configuration file. Nosotros will utilise the dotenv bundle; we likewise demand the Node.js SDK for Google API. So, within the terminal at the project root, run the code beneath 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 up src/alphabetize.ts and type the code beneath save and run the code yarn first to see the result:

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

Interact with Google Drive API

Nosotros will create a file named googleDriveService which 4 methods:

  • createDriveClient(): create a client with the credentials generated earlier, and we will apply information technology to make calls to Google Drive API
  • searchFolder(): Search a folder inside Google Drive.
  • createFolder(): Create a new folder inside Google Bulldoze
  • saveFile(): Create a new file in a folder within Google Bulldoze
                import fs from 'fs'; // eslint-disable-next-line @typescript-eslint/no-var-requires const { google } = require('googleapis');  /**  * Browse the link below 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: cord;   name: cord; };  type SearchResultResponse = {   kind: 'bulldoze#fileList';   nextPageToken: string;   incompleteSearch: boolean;   files: PartialDriveFile[]; };  consign class GoogleDriveService {   individual driveClient;    public constructor(clientId: string, clientSecret: cord, redirectUri: string, refreshToken: string) {     this.driveClient = this.createDriveClient(clientId, clientSecret, redirectUri, refreshToken);   }    createDriveClient(clientId: string, clientSecret: cord, redirectUri: cord, 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): Hope<PartialDriveFile> {     return this.driveClient.files.create({       resources: {         name: folderName,         mimeType: 'awarding/vnd.google-apps.binder',       },       fields: 'id, name',     });   }    searchFolder(folderName: cord): Promise<PartialDriveFile | null> {     return new Promise((resolve, reject) => {       this.driveClient.files.list(         {           q: `mimeType='application/vnd.google-apps.folder' and name='${folderName}'`,           fields: 'files(id, name)',         },         (err, res: { data: SearchResultResponse }) => {           if (err) {             render refuse(err);           }            return resolve(res.information.files ? res.data.files[0] : null);         },       );     });   }    saveFile(fileName: string, filePath: string, fileMimeType: cord, folderId?: cord) {     return this.driveClient.files.create({       requestBody: {         name: fileName,         mimeType: fileMimeType,         parents: folderId ? [folderId] : [],       },       media: {         mimeType: fileMimeType,         body: fs.createReadStream(filePath),       },     });   } }              
Content of file src/googleDriveService.ts

Now let'southward utilize the GoogleDriveService in our alphabetize.ts file so replace the content by the i beneath:

                import dotenv from 'dotenv'; import * as path from 'path'; import * as 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 = 'Film';    if (!fs.existsSync(finalPath)) {     throw new Fault('File not found!');   }    allow folder = await googleDriveService.searchFolder(folderName).grab((error) => {     console.error(mistake);     return null;   });    if (!folder) {     folder = await googleDriveService.createFolder(folderName);   }    await googleDriveService.saveFile('SpaceX', finalPath, 'image/jpg', folder.id).catch((error) => {     console.mistake(error);   });    console.info('File uploaded successfully!');    // Delete the file on the server   fs.unlinkSync(finalPath); })();              
Content of file src/index.ts

Type yarn offset to kickoff the application and run across the event:

The picture was uploaded to Google Drive successfully. 🎉

You tin can establish the source code of this tutorial at this link.

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

valdezanther.blogspot.com

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

0 Response to "How to See Google Drive Api Upload File"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel