Welcome folks today in this blog post we will be uploading files to google drive folder
using the oauth2 & fetch api post method in browser using javascript. All the full source code of the application is shown below.
Get Started
The directory structure of the app is shown below
In order to get started you need to create the index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!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>OAuth2 Google SignIn With Logout</title> </head> <body> <h1>OAuth2 Google Sign-In</h1> <button id="button">Sign In With Google</button> </body> <script type="module" src="script.js"></script> </html> |
As you can see inside this html
code we are showing the google login
button and then we have also given the id
parameter to the button
of google login. And after that we are including the script.js
file and we have attached the type
property to module so that we can use the imports and exports statement.
Now need to make the utils.js
file inside the same directory and here we will be defining the four
methods which will be required for oauth2 signIn
and signout
.
utils.js
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 |
function signIn(clientId,redirectUri,scopes,response_type="token") { let oauth2Endpoint = "https://accounts.google.com/o/oauth2/v2/auth"; let form = document.createElement("form"); form.setAttribute("method", "GET"); form.setAttribute("action", oauth2Endpoint); let params = { client_id: clientId, redirect_uri: redirectUri, response_type: response_type, scope: scopes, include_granted_scopes: "true", state: "pass-through-value", }; for (var p in params) { let input = document.createElement("input"); input.setAttribute("type", "hidden"); input.setAttribute("name", p); input.setAttribute("value", params[p]); form.appendChild(input); } document.body.appendChild(form); form.submit(); } |
Basically this is the first method of oauth2 signin
where we are passing four parameters which is the clientid
,redirecturi
,scopes and response_type as arguments to this function. And inside this function we are making a simple GET Request to the endpoint passing these parameters. And then submitting the form programatically.
Logout() Function
1 2 3 4 5 6 7 8 9 10 |
function logout(access_token, redirect_url) { fetch("https://oauth2.googleapis.com/revoke?token=" + access_token, { method: "POST", headers: { "Content-type": "application/x-www-form-urlencoded", }, }).then((data) => { location.href = redirect_url; }); } |
As you can see inside the above function we are taking the accessToken
and redirect_uri
as arguments. And inside this we are making a simple fetch
api request here we are passing the method to be GET
and then we are passing the headers of Content-Type
And now we will be writing the function to get the params
from the url as shown below. Here we will be getting the access_token
from the url
1 2 3 4 5 6 7 8 9 10 11 12 |
function getParamsFromURL(url) { let params = {}; let regex = /([^&=]+)=([^&]*)/g, m; while ((m = regex.exec(url))) { params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); } return params; } |
Now we will be defining the oauth2
data inside the localstorage as shown below
1 2 3 4 5 6 7 8 9 10 |
function saveOAuth2Info(data, path, name) { if (Object.keys(data).length > 0) { localStorage.setItem(name, JSON.stringify(data)) } // hide the access token window.history.pushState({}, document.title, "/" + path) } |
Here in the above method we are using the setItem()
to store the oauth2
object in the localstorage. And then we are using the pushState()
method to hide
the params inside the url.
Now we need to export the above defined methods using the export
statement as shown below
1 2 3 4 5 6 |
export default{ signIn, logout, saveOAuth2Info, getParamsFromURL } |
Now we need to define the script.js
file as shown below
script.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import utils from './utils.js' let CLIENT_ID = "##yourclientid##" let REDIRECT_URI = "##yourredirecturl##" let SCOPES = "https://www.googleapis.com/auth/drive" let button = document.getElementById('button') button.addEventListener('click',signIn) function signIn(){ utils.signIn(CLIENT_ID,REDIRECT_URI,SCOPES) } |
As you can see we are importing the utils.js
file and then we are defining the clientId
and redirect_uri.
And also we are defining the scopes
as well. In this case we will be providing the drive
scopes. And then we are defining the onclick event listener to the signin button. And we have defined the signIn()
method we are calling the signIn()
method from the utils.js file and here we are passing the clientid
and redirecturi
.
You can create the clientid in the google developer console as shown below
And now if you open the index.html
and press the signIn
button you will see the below result
As you can see after you grant the access to the permissions in the oauth2 consent screen we are getting the accessToken
in the url of the browser as shown above.
And now we need to define the profile.html
file and copy paste the below code
profile.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!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>Google Drive Upload File in Javascript</title> </head> <body> <form id="form"> <input type="file" multiple name="file" id="files"> <input type="submit" value="Upload File"> </form> <button id="logout">Logout</button> </body> <script type="module" src="profile.js"></script> </html> |
As you can see in the above code we are making the form in which we have the input field to upload the file from the computer And then we have the submit button to submit the form. And also we have the logout button.
And now we need to make the profile.js
file and copy paste the below code
profile.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import utils from "./utils.js"; let params = utils.getParamsFromURL(location.href); let ACCESS_TOKEN = ""; let redirect_url = "http://127.0.0.1:5500/index.html"; let button = document.getElementById("logout"); let fileImage = document.getElementById("files"); console.log(params); utils.saveOAuth2Info(params, "profile.html", "info"); let info = JSON.parse(localStorage.getItem("info")); ACCESS_TOKEN = info.access_token; |
As you can see we are importing the utils.js
file and then we are getting the params from the url. And then we are declaring the variables for access_token,redirect_uri and button variable for logout. And then we are getting the reference of the input element having the id called files
. And then we are calling the oauth2Info() method to save the info inside the localstorage. And then we are storing the access_token
inside the localstorage.
And we will be attaching the onsubmit
event handler to the form element as shown below
1 |
form.onsubmit = uploadFile; |
So when the form submits when we upload the file and then click the submit button we are calling the uploadFile()
method and now we will be defining the function as shown below
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 32 33 34 |
function uploadFile(e) { e.preventDefault(); console.log(file.files[0]) var metadata = { name: Date.now() + file.files[0].name, // Filename at Google Drive mimeType:file.files[0].type, // 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", file.files[0]); 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); file.value = ""; alert("file Uploaded") }); } |
As you can see we will declaring the metadata
object in which we are having the name of the file
which will be uploaded and also we are providing the mimetype of the uploaded file. And then we are providing the parents
property for upload to a specific folder using it’s id. And then we are making the new formData
object. And then we are calling the append()
method to store the uploaded
file metadata and then actual file. And then we are making the simple fetch api
post request to the url
and then we are also passing the headers object as well. And then we are passing the accessToken
in it. And then we are also passing the formData
object in the body field of the request. And it returns the promise using the then()
method. And then we are converting the response to json using the json()
. You will see the below result after you submit the form
As you can see we are getting the id
of the uploaded file in google drive. Now if we check on google drive you will see the below result
And now we will be defining the logout()
function on the button click as shown below
1 2 3 4 5 |
button.onclick = logout; function logout() { utils.logout(ACCESS_TOKEN, redirect_url); } |
FULL SOURCE CODE