Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Javascript Google Drive API Example to Capture Image From Webcam & Upload to Drive Using OAuth2 in Browser

Posted on December 5, 2022

 

 

Welcome folks today in this blog post we will be building a simple web app where we will be capturing the image from the webcam and upload it to google drive using oauth2 and drive api in javascript. All the full source code of the application is shown below.

 

 

 

Get Started

 

 

In order to get started you need to read the blog post where we have shown how to build a simple oauth2 google login and logout system using  the access token. You need to read the below blog post before you read this one. The link is shown below

 

 

Javascript OAuth2 Google Login & Logout Example Using Access Token in Browser

 

 

And after this you will see the below directory structure of the project as shown below

 

 

 

 

 

And now we need to modify the profile.html file and inside it you need to copy paste the below code

 

 

profile.html

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Capture Image From Webcam & Upload to Google Drive</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <video width="200" height="200" autoplay="true" id="video">
        </video>
        <button id="capture">Capture & Upload to Google Drive</button>
        <canvas id="canvas" style="overflow:auto"></canvas>
        <br></br>
        <p> Image Converted to String: </p>
        <p id="printresult"></p>
        <button id="logout">Logout</button>
    </div>
</body>
<script type="module" src="profile.js"></script>
 
</html>

 

 

As you can see inside the above html code we are having the video tag inside that we will be displaying the webcam video feed and we are also attaching the autoplay attribute to make sure the webcam video will be playing once you load the page. And then we have the button to capture the image and also we have the canvas element to capture the image. And then we have the logout button also to logout from the oauth2 google account.

 

 

Displaying Webcam Video Feed

 

 

Now guys we will be displaying the webcam video feed of the user using some javascript in profile.js file as shown below

 

 

profile.js

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
var video = document.querySelector("#video");
if (navigator.mediaDevices.getUserMedia) {
  navigator.mediaDevices
    .getUserMedia({ video: true })
    .then(function (stream) {
      video.srcObject = stream;
    })
    .catch(function (err0r) {
      console.log("Something went wrong!");
    });
}

 

 

As you can see in the above javascript code we are getting the reference of the video dom element. And also we are using the navigator api to get access to the user webcam using the getUserMedia() method and inside that we are passing the video option to true. And then inside the promise we are attaching the webcam video feed to the video srcobject. Now if you open the web app inside the browser you will see the below result. First of all you need to allow the permission to get access to the webcam

 

 

 

 

 

 

And now we need to add the onclick event listener to the capture button to take the screenshot from the webcam and automatically upload it to google drive

 

 

JavaScript
1
2
3
let capture = document.getElementById("capture");
 
capture.onclick = captureAndUploadToDrive;

 

 

And now we need to define the above function as shown below

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
function captureAndUploadToDrive() {
  var canvas = document.getElementById("canvas");
  var video = document.getElementById("video");
  canvas.width = 1280;
  canvas.height = 720;
  canvas.getContext("2d").drawImage(video, 0, 0, 1280, 720);
  resultb64 = canvas.toDataURL();
  let blob = dataURItoBlob(resultb64)
  console.log(blob)
  uploadFile(blob)
  document.getElementById("printresult").innerHTML = canvas.toDataURL();
}

 

 

As you can see guys inside the above function we are first of all we are getting the references of the canvas and the video elements. And then we are attaching the custom width and height to the canvas. And then we are getting the context of the 2d canvas and we are drawing the image inside the canvas passing the width and the height. And then we are converting the canvas image to base64 data url using the toDataURL() method. And after that we are converting the base64 data url to blob file using the dataURItoBlob() custom method we are calling it and passing the base64 code to that function and after that we are calling the uploadFile() function to upload it to google drive.

 

Now we need to define the dataURItoBlob() custom method and copy paste the below code

 

 

JavaScript
1
2
3
4
5
6
7
8
function dataURItoBlob(dataURI) {
  var binary = atob(dataURI.split(',')[1]);
  var array = [];
  for (var i = 0; i < binary.length; i++) {
      array.push(binary.charCodeAt(i));
  }
  return new Blob([new Uint8Array(array)], { type: 'image/jpeg' });
}

 

 

As you can see in the above code we are getting the base64 url from the argument and inside that we are using the atob() method and after that we are using the Uint8Array()  method to convert base64 to Blob.

 

And now we will be defining the uploadFile() method to upload the captured image from the webcam and upload it to google drive as shown below

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function uploadFile(blob) {
 
  var metadata = {
    name: Date.now() + "image.jpg", // Filename at Google Drive
    mimeType: "image/jpg", // mimeType at Google Drive
    //parents: ["##googldrivefolderid##"], // Folder ID at Google Drive
  };
 
  var form = new FormData();
  form.append(
    "metadata",
    new Blob([JSON.stringify(metadata)], { type: "application/json" })
  );
  form.append("userpic", blob);
 
  fetch(
    "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id",
    {
      method: "POST",
      headers: new Headers({ Authorization: "Bearer " + ACCESS_TOKEN }),
      body: form,
    }
  )
    .then((res) => {
      return res.json();
    })
    .then(function (val) {
      console.log(val);
      alert("file Uploaded");
    });
}

 

 

As you can see in the above code we are using the same logic where we are using the fetch api to make a simple POST request to the google drive to upload the captured image from the webcam. We have used the same code in the simple example where we have uploaded the local image from the computer and upload it to google drive. I have explained all the things that we are doing in the above example. I think you should read the below blog post to upload a local image to google drive as shown below

 

 

Javascript OAuth2 Google Drive Upload File to Folder Using Fetch API & HTTP POST Method in Browser

 

 

And now if you open the web app you will see the below result

 

 

 

 

 

GITHUB REPOSITORY

 

Recent Posts

  • Android Java Project to Merge Multiple PDF Documents From Gallery Using iTextPDF Library
  • Android Java Project to Detect System Hardware & System CPU Info & Display inside TextView Widget
  • Android Java Project to Integrate Google OAuth2 Login & Logout System & Save User Info in SharedPreferences
  • Android Java Project to Export Raw Text to PDF Document Using iTextPDF Library
  • Android Java Project to Export Images From Gallery to PDF Document Using iTextPDF Library
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme