Uploading files to google drive from Nodejs using google drive API

Murali mahadeva B S
3 min readJun 16, 2021

⭐This will be about how to upload files to google drive using its API(OAuth credentials).
Requirement: A google account.

Depiction of file upload from nodejs to google drive

Table of contents:

  1. Creating Access token and Refresh token (jwt)
  2. Uploading files from Nodejs
  3. Uploading files from Reactjs through Nodejs

Creating Access token and Refresh token

  1. Go to google cloud platform console using your account.
  2. Create a new project and enable google drive API services for that project.
  3. Go to credentials menu and click on create new OAuth client ID.
  4. It will ask you to configure consent screen. In User type select External and click create. Fill in app information, Leave the app logo field empty.
    If you upload app logo, it’ll take time for verification
    . Leave the app domain fields empty. Click save and continue.
  5. In Scopes tab continue without any changes to next step.
  6. In Test users tab, add the gmailID from which account you want to test and click on go to dashboard in the last step.
  7. Click on create credentials again and select create OAuth client id. Select type of application to web application. Fill in your app name and add https://developers.google.com/oauthplayground in redirect URL tab.
    ⚠️Note: don’t add / in the end of the above URL.
    and click on create. You will get a client id and client secret.
  8. In oauthplayground select drive and click on first URL. Click on settings icon from top right corner and check “User your own OAuth credentials” and fill in your client id and client secret from before.
  9. Once you click on Authorize API’s it’ll authorize your google account and generate Access token and Refresh token.
Google OAuth playground

Uploading files from Nodejs

  1. Install googleapis npm package.
const { google } = require("googleapis");
const fs = require('fs');
const { CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, REFRESH_TOKEN } = process.env;const oauth2client = new google.auth.OAuth2(
CLIENT_ID,
CLIENT_SECRET,
REDIRECT_URI
);
oauth2client.setCredentials({ refresh_token: REFRESH_TOKEN });
const drive = google.drive({
version: "v3",
auth: oauth2client,
});
let resp = await drive.files.create(
{
requestBody: {
name: "file.png",
MimeType: "image/png",
},
media: {
MimeType: "image/png",
body: fs.createReadStream(filePath),
}
}
);

2. I’m getting clientid, client secret, redirect uri and refresh token from .env file. Above code will upload the file to google drive.
↪️ You can use access token in place of refresh token but access token expires after an hour or so. You can use refresh token to get new access token hitting oauthplayground url.

let resp = await drive.files.delete(
{
fileId:'sdljsldjfsldjflsldjfljsdlfj'
}
);

Using the fileId you get from response after upload you can delete the file.

await drive.permissions.create({
fileId,
requestBody: {
role: "reader",
type: "anyone",
},
});
let result = await drive.files.get({
fileId,
fields: "webContentLink, webViewLink",
});

Using the above lines you can generate a public download link and view link. webContentLink is the download link. webViewLink is the online view link.

Uploading files from Reactjs to google drive through Nodejs

🟡Reactjs part:

let formdata = new FormData();
formdata.append("file", content);
let headers = {
"Content-Type": "multipart/form-data",
};
let resp = await axios({
url,
method: "POST",
data: formdata,
headers,
});

🟡Nodejs setup:
I’m using formidable npm package with expressjs to parse the formdata. You can use multer or any other package.

let form = new formidable({ multiples: true });
form.parse(req, async function (err, fields, files) {
if (err) {
console.log("Error in parsing formidable form");
};
let filePath = files.file.path;
let fileName = files.file.name;
let fileType = files.file.type;
let fileSize = files.file.size;

try {
let resp = await drive.files.create(
{
requestBody: {
name: fileName,
MimeType: fileType,
},
media: {
MimeType: fileType,
body: fs.createReadStream(filePath),
},
},
{
onUploadProgress: (evt) => {
const progress = Math.floor((evt.bytesRead / fileSize) * 100);
console.log("progress:", progress);

},
}
);

In createReadStream() you can pass the client file path to create a stream to upload to google drive.
↪️ You can get the upload progress from onUploadProgress.

⚠️Note: Not just Reactjs you can parse the files from html form and upload them also.

Thank yourself for learning something new

Stay curious… stay creative…

--

--