Oh Snap!

Please turnoff your ad blocking mode for viewing your site content

Hit enter after type your search item

Node.js Express Google Drive API Upload File Using Google-Apis Client Library Full Project

/
/
/
337 Views

Welcome folks today in this blog post we will be building a application in node.js express where we will be uploading files in our application.We will have a graphical user interface where users will be first authenticated and then we will have the simple form to upload the file to google drive. The screenshot of the application is give below. And all the source code is also given below to download. A step by step youtube video is also given below to follow with the blog.

 

 

Screenshots

 

 

Requirements

 

Express : Server on which the app will be running

googleapis : It will be the official google client library for authentication for node.js. We will be using this library for authentication

fs: we will be using this file system module which is built in module for nodejs to store files

multer: This will be the library for uploading files on the express server

ejs: It will be the template engine which will be used in the node.js application

nodemon: It will be the library to automatically restart the application when any changes takes place

 

const fs = require("fs");
const express = require("express");
const multer = require("multer");
const OAuth2Data = require("./credentials.json");
var name,pic

const { google } = require("googleapis");

const app = express();


const CLIENT_ID = OAuth2Data.web.client_id;
const CLIENT_SECRET = OAuth2Data.web.client_secret;
const REDIRECT_URL = OAuth2Data.web.redirect_uris[0];

const oAuth2Client = new google.auth.OAuth2(
  CLIENT_ID,
  CLIENT_SECRET,
  REDIRECT_URL
);
var authed = false;

// If modifying these scopes, delete token.json.
const SCOPES =
  "https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/userinfo.profile";

app.set("view engine", "ejs");

var Storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, "./images");
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
  },
});

var upload = multer({
  storage: Storage,
}).single("file"); //Field name and max count

app.get("/", (req, res) => {
  if (!authed) {
    // Generate an OAuth URL and redirect there
    var url = oAuth2Client.generateAuthUrl({
      access_type: "offline",
      scope: SCOPES,
    });
    console.log(url);
    res.render("index", { url: url });
  } else {
    var oauth2 = google.oauth2({
      auth: oAuth2Client,
      version: "v2",
    });
    oauth2.userinfo.get(function (err, response) {
      if (err) {
        console.log(err);
      } else {
        console.log(response.data);
        name = response.data.name
        pic = response.data.picture
        res.render("success", {
          name: response.data.name,
          pic: response.data.picture,
          success:false
        });
      }
    });
  }
});

app.post("/upload", (req, res) => {
  upload(req, res, function (err) {
    if (err) {
      console.log(err);
      return res.end("Something went wrong");
    } else {
      console.log(req.file.path);
      const drive = google.drive({ version: "v3",auth:oAuth2Client  });
      const fileMetadata = {
        name: req.file.filename,
      };
      const media = {
        mimeType: req.file.mimetype,
        body: fs.createReadStream(req.file.path),
      };
      drive.files.create(
        {
          resource: fileMetadata,
          media: media,
          fields: "id",
        },
        (err, file) => {
          if (err) {
            // Handle error
            console.error(err);
          } else {
            fs.unlinkSync(req.file.path)
            res.render("success",{name:name,pic:pic,success:true})
          }

        }
      );
    }
  });
});

app.get('/logout',(req,res) => {
    authed = false
    res.redirect('/')
})

app.get("/google/callback", function (req, res) {
  const code = req.query.code;
  if (code) {
    // Get an access token based on our OAuth code
    oAuth2Client.getToken(code, function (err, tokens) {
      if (err) {
        console.log("Error authenticating");
        console.log(err);
      } else {
        console.log("Successfully authenticated");
        console.log(tokens)
        oAuth2Client.setCredentials(tokens);


        authed = true;
        res.redirect("/");
      }
    });
  }
});

app.listen(5000, () => {
  console.log("App is listening on Port 5000");
});

 

<!doctype html>
<html>
<head>
    <title>Node Authentication</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
    <style>
        body        { padding-top:80px; }
    </style>
</head>
<body>
<div class="container">

    <div class="jumbotron text-center">
        <h1><span class="fa fa-lock"></span> Node Google Drive Upload</h1>

        <p>Login or Register with:</p>

        <a href="<%=url%>" class="btn btn-danger"><span class="fa fa-google-plus"></span> Google</a>

    </div>

</div>
</body>
</html>

 

<!DOCTYPE html>
<html>
  <head>
    <title>Node Authentication</title>
    <link
      rel="stylesheet"
      href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"
    />
    <link
      rel="stylesheet"
      href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"
    />
    <style>
      body {
        padding-top: 80px;
        word-wrap: break-word;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="page-header text-center">
        <h1><span class="fa fa-anchor"></span> Profile Page</h1>
        <a href="/logout" class="btn btn-default btn-sm">Logout</a>
      </div>

      <div class="row">
        <!-- GOOGLE INFORMATION -->
        <div class="col-sm-6">
          <div class="well">
            <h3 class="text-danger">
              <span class="fa fa-google-plus"></span> Google
            </h3>

            <p>
              <strong>name</strong>: <%= name %>
              <br />
              <strong>pic:</strong>:
              <img src="<%=pic%>" width="200" height="200" alt="" />
            </p>
          </div>
        </div>

        <div class="col-sm-6">
          <div class="well">
            <h3 class="text-danger">
              <span class="fa fa-google-plus"></span> Upload File to Google
              Drive
            </h3>

            <% if (success) { %>
            <div class="alert alert-success alert-dismissible">
              <a href="#" class="close" data-dismiss="alert" aria-label="close"
                >×</a
              >
              <strong>Success!</strong> Your Image File is Uploaded.
            </div>
            <%}%>
            <form action="/upload" method="POST" enctype="multipart/form-data">
              <div class="form-group">
                <input
                  type="file"
                  class="form-control"
                  name="file"
                  required
                  id=""
                />
              </div>
              <div class="form-group">
                <button class="btn btn-block btn-danger">
                  Upload File
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</html>

 

READ  jQuery Plugin For Easy Youtube Video Embedding - EasyEmbed

 

DOWNLOAD SOURCE CODE

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This div height required for enabling the sticky sidebar
Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views :