Created
September 1, 2021 17:36
-
-
Save itsTeknas/228ef4daf5809043b525241ee19b33fd to your computer and use it in GitHub Desktop.
Google Drive File Upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>GDrive File Upload</title> | |
<meta charset="utf-8" /> | |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.0/css/bootstrap.min.css" | |
integrity="sha512-F7WyTLiiiPqvu2pGumDR15med0MDkUIo5VTVyyfECR5DZmCnDhti9q5VID02ItWjq6fvDfMaBaDl2J3WdL1uxA==" | |
crossorigin="anonymous" referrerpolicy="no-referrer" /> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" | |
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" | |
crossorigin="anonymous" referrerpolicy="no-referrer"></script> | |
</head> | |
<body> | |
<div class="container"> | |
<header class="d-flex flex-wrap justify-content-center py-3 mb-4 border-bottom"> | |
<a href="/" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-dark text-decoration-none"> | |
<span class="fs-4">GDrive File Upload</span> | |
</a> | |
<button class="btn btn-danger" id="signout_button" style="display: none;">Sign Out</button> | |
</header> | |
</div> | |
<div id="signed_out_placeholder" class="container py-4"> | |
<div class="p-5 mb-4 bg-light rounded-3"> | |
<div class="container-fluid py-5"> | |
<h1 class="display-5 fw-bold">Authorize to begin</h1> | |
<p class="col-md-8 fs-4">We will need to first sign in with google with the google drive scope added so we can interact with the gdrive api</p> | |
<button class="btn btn-success btn-lg" id="authorize_button" style="display: none;" type="button">Authorize</button> | |
</div> | |
</div> | |
</div> | |
<div class="container"> | |
<div id="uploaderContainer" class="row"> | |
<div class="col"> | |
<div class="input-group mb-3"> | |
<input id="fileInput" type="file" class="form-control" placeholder="Select File"> | |
<button id="uploadBtn" class="btn btn-success" type="button" id="button-addon2">Upload</button> | |
</div> | |
</div> | |
<div class="col-12"> | |
<pre id="content" style="white-space: pre-wrap;"></pre> | |
</div> | |
</div> | |
</div> | |
<script type="text/javascript"> | |
// Client ID and API key from the Developer Console | |
var CLIENT_ID = 'XXXXXX.apps.googleusercontent.com'; | |
var API_KEY = 'XXXXXX'; | |
// Array of API discovery doc URLs for APIs used by the quickstart | |
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"]; | |
// Authorization scopes required by the API; multiple scopes can be | |
// included, separated by spaces. | |
var SCOPES = 'https://www.googleapis.com/auth/drive'; | |
var authorizeButton = document.getElementById('authorize_button'); | |
var signoutButton = document.getElementById('signout_button'); | |
/** | |
* On load, called to load the auth2 library and API client library. | |
*/ | |
function handleClientLoad() { | |
gapi.load('client:auth2', initClient); | |
} | |
/** | |
* Initializes the API client library and sets up sign-in state | |
* listeners. | |
*/ | |
function initClient() { | |
gapi.client.init({ | |
apiKey: API_KEY, | |
clientId: CLIENT_ID, | |
discoveryDocs: DISCOVERY_DOCS, | |
scope: SCOPES | |
}).then(function () { | |
// Listen for sign-in state changes. | |
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); | |
// Handle the initial sign-in state. | |
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get()); | |
authorizeButton.onclick = handleAuthClick; | |
signoutButton.onclick = handleSignoutClick; | |
}, function (error) { | |
appendPre(JSON.stringify(error, null, 2)); | |
}); | |
} | |
/** | |
* Called when the signed in status changes, to update the UI | |
* appropriately. After a sign-in, the API is called. | |
*/ | |
function updateSigninStatus(isSignedIn) { | |
if (isSignedIn) { | |
authorizeButton.style.display = 'none'; | |
signoutButton.style.display = 'block'; | |
$("#uploaderContainer").show() | |
$("#signed_out_placeholder").hide() | |
listFiles(); | |
} else { | |
authorizeButton.style.display = 'block'; | |
signoutButton.style.display = 'none'; | |
$("#uploaderContainer").hide() | |
$("#signed_out_placeholder").show() | |
} | |
} | |
/** | |
* Sign in the user upon button click. | |
*/ | |
function handleAuthClick(event) { | |
gapi.auth2.getAuthInstance().signIn(); | |
} | |
/** | |
* Sign out the user upon button click. | |
*/ | |
function handleSignoutClick(event) { | |
gapi.auth2.getAuthInstance().disconnect(); | |
} | |
/** | |
* Append a pre element to the body containing the given message | |
* as its text node. Used to display the results of the API call. | |
* | |
* @param {string} message Text to be placed in pre element. | |
*/ | |
function appendPre(message) { | |
var pre = document.getElementById('content'); | |
var textContent = document.createTextNode(message + '\n'); | |
pre.appendChild(textContent); | |
} | |
/** | |
* Print files. | |
*/ | |
function listFiles() { | |
$("#content").empty() | |
gapi.client.drive.files.list({ | |
'pageSize': 10, | |
'fields': "nextPageToken, files(id, name)" | |
}).then(function (response) { | |
appendPre('Files in drive:'); | |
var files = response.result.files; | |
if (files && files.length > 0) { | |
for (var i = 0; i < files.length; i++) { | |
var file = files[i]; | |
appendPre(file.name); | |
} | |
} else { | |
appendPre('No files found.'); | |
} | |
}); | |
} | |
function uploadFile(file) { | |
var metadata = { | |
'name': file.name, // Filename at Google Drive | |
'mimeType': file.type, // mimeType at Google Drive | |
originalFilename: file.name, | |
}; | |
var formData = new FormData(); | |
formData.append("metadata", new Blob([JSON.stringify(metadata)], { type: "application/json" })); | |
formData.append("file", file); | |
fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart", { | |
method: "POST", | |
headers: new Headers({ "Authorization": "Bearer " + gapi.auth.getToken().access_token }), | |
body: formData | |
}).then(function (response) { | |
return response.json(); | |
}).then(function (value) { | |
console.log(value); | |
alert("File Uploaded") | |
listFiles() | |
}); | |
} | |
$(document).ready(() => { | |
$("#uploadBtn").click(() => { | |
let file = null; | |
try { | |
file = $('#fileInput')[0].files[0] | |
console.log(file) | |
} catch (ignore) { } | |
if (file) { | |
uploadFile(file) | |
} else { | |
alert("Please select a file") | |
} | |
}) | |
}) | |
</script> | |
<script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()" | |
onreadystatechange="if (this.readyState === 'complete') this.onload()"> | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment