Image Distorts When I Upload Excel to Google Drive

We demand to follow the below steps to upload whatever file to upload in google drive through nodejs. For at present, volition show an example to upload an paradigm on google drive.

  • Turn on the Drive API

click this button to enable the Drive API:

After clicking on enable push i dialogue box will open, from at that place y'all will become customer credentials and it will automatically download the file in your system.

The file volition accept a Client ID and Client Secret which nosotros should non expose to others for security purpose.

Install the customer library

In your existing projection, you demand to install this library to implement this feature.

If yous are creating this feature as a separate projection then yous need to create a nodejs uncomplicated project like you need to do npm init that it will create package.json in your folder and afterward yous can create ane file which will accept this functionality of uploading the file on google drive

npm          install          googleapis@39                  

After that create a file named uploadimage.js

          const          fs =          crave('fs');          const          readline =          require('readline');          const          {google} =          require('googleapis');        

We need to install the higher up packages first fs(filesystem) which will read-write into a file and do many operations much of you lot will aware of this packet as its basic ane.

some other package is readline (module provides a way of reading a data stream, one line at a time).

another i is googleapis(customer library for using Google APIs. Support for dominance and authentication with OAuth 2.0, API Keys and JWT tokens is included.) which helps us to upload the file here.

          const          fs =          require('fs');          const          readline =          require('readline');          const          {google} =          require('googleapis');          const          SCOPES = ['https://www.googleapis.com/auth/bulldoze'];          const          TOKEN_PATH =          'token.json';   fs.readFile('credentials.json', (err, content) => {          if          (err)          return          console.log('Error loading client secret file:', err);    authorize(JSON.parse(content), storeFiles); });                      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]);      fs.readFile(TOKEN_PATH, (err, token) => {          if          (err)        {          return          getAccessToken(oAuth2Client, callback);              }       oAuth2Client.setCredentials(JSON.parse(token));       callback(oAuth2Client);     });   }                      function            getAccessToken(oAuth2Client, callback)          {          const          authUrl = oAuth2Client.generateAuthUrl({       access_type:          'offline',       scope: SCOPES,     });          console.log('Authorize this app past visiting this url:', authUrl);          const          rl = readline.createInterface({       input: process.stdin,       output: procedure.stdout,     });     rl.question('Enter the code from that folio here: ', (code) => {       rl.shut();       oAuth2Client.getToken(code, (err, token) => {          if          (err)          return          panel.error('Error retrieving admission token', err);         oAuth2Client.setCredentials(token);            fs.writeFile(TOKEN_PATH,          JSON.stringify(token), (err) => {          if          (err)          return          console.error(err);         });         callback(oAuth2Client);       });     });   }                      role            storeFiles(auth)          {          panel.log("auth",          JSON.stringify(auth));          const          bulldoze = google.bulldoze({version:          'v3', auth});          var          fileMetadata = {          'proper noun':          'ImageTest.jpeg'          };          var          media = {             mimeType:          'prototype/jpeg',                          body: fs.createReadStream('C:/Users/bhavya.jain/Downloads/traveltattoo.jpg')     };     drive.files.create({         resource: fileMetadata,         media: media,         fields:          'id'          },                      function            (err, file)          {          if          (err) {                   panel.fault(err);     }          else          {          console.log('File Id: ', file.data.id);     }  });   }        

In the above piece of lawmaking, we need to accept care of a few things.

like If modifying these scopes for changing the permission to access our google drive, delete token.json. The file token.json stores the user'south admission and refresh tokens, and is created automatically when the authorization catamenia completes for the first time.

And every time it won't delete token.json or override the file, it will be same. Every bit I mentioned above for modifying the token.json we demand to delete it first.

fs.readfile will but load client secrets from a local file. After that information technology authorizes client credentials, so telephone call the Google Drive API.

We need to validate if we have previously stored a token. If the previous token is not there and then we demand to Store the token to disk for afterwards program executions which nosotros are doing here by calling getAccessToken.

Then finally we demand to call the chief function storeFiles which perform a major task to upload file in google bulldoze. The file we demand to upload from the system for that we need to provide a path of the file from our organization.

In fileMetadata, we tin give whatever proper noun we crave. Here I have given ImageTest.jpeg.

Finally, nosotros need to run node uploadimage.js

The first time yous run the file, it volition prompt you lot to qualify access:

  • y'all need to browse to the provided URL in your web browser.
  • If you are not already logged into your Google account, you will exist prompted to log in. If you are logged into multiple Google accounts, you volition exist asked to select one account to utilize for the say-so.
  • Click the Accept button.
  • Copy the lawmaking you're given, paste it into the command-line prompt, and press Enter.

And here we get we have saved our epitome in google drive every bit shown in beneath image.

No alt text provided for this image

I hope this article helps many people who faced the issue in uploading the file on google drive.

weeksjuseenoth.blogspot.com

Source: https://www.linkedin.com/pulse/upload-file-google-drive-nodejs-bhavya-jain

0 Response to "Image Distorts When I Upload Excel to Google Drive"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel