Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Upload Files to Google Drive with JavaScript

#1
How to Upload Files to Google Drive with JavaScript

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/08/how-to-upload-files-to-google-drive-with-javascript.jpg" width="550" height="580" title="" alt="" /></div><div><div class="modified-on" readability="7.1111111111111"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on August 15th, 2022.</div>
<p>This article gives a working example script to learn how to upload files to Google Drive via JavaScript.</p>
<p>Creating a JavaScript solution to the Drive file upload process is very simple. It uses&nbsp;<strong><em>gapi</em></strong> library to implement this feature on the client side.</p>
<p>In a recently posted tutorial, we created an example code for achieving <a href="https://phppot.com/php/how-to-upload-files-to-google-drive-with-api-using-php/">Google Drive upload in PHP</a>.</p>
<h2>Prerequisites</h2>
<p>It needs two libraries loaded to achieve JavaScript via Google Drive upload.</p>
<ol>
<li><a href="https://phppot.com/php/php-google-oauth-login/">Google sign-in</a> library for identity verification.</li>
<li>Google API client library for JavaScript-based API access.</li>
</ol>
<p>Added to that, create the API app and get the credentials.</p>
<ol>
<li>Enable the Google Drive API.</li>
<li>Get the API key and Web client id from the Google developer console.</li>
</ol>
<p>Go to the Google developer console and click “Create Credentials” to set the <em>API key</em> and <em>web client id</em>. We have seen how to get the Google API keys from the developer console in previous articles.</p>
<h2>Steps to upload files to Google Drive with JavaScript</h2>
<p>These are the steps to implement uploading files from an application to Google Drive using JavaScript.</p>
<ol>
<li>Authorize by proving the identity via Google sign-in API (GSI) library challenge.</li>
<li>Get the access token.</li>
<li>Prepare the upload request by specifying the Google drive directory target (optional).</li>
<li>Hit Google Drive V3 endpoint to <a href="https://phppot.com/php/multiple-file-upload-using-fine-uploader/">post file content and metadata</a> via JavaScript FormData.</li>
</ol>
<p><img loading="lazy" class="alignnone size-large wp-image-18960" src="https://phppot.com/wp-content/uploads/2022/08/authorize-and-upload-to-google-drive-550x580.jpg" alt="authorize and upload to google drive" width="550" height="580" srcset="https://phppot.com/wp-content/uploads/2022/08/authorize-and-upload-to-google-drive-550x580.jpg 550w, https://phppot.com/wp-content/uploads/20...84x300.jpg 284w, https://phppot.com/wp-content/uploads/20...68x810.jpg 768w, https://phppot.com/wp-content/uploads/20...-drive.jpg 800w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>Example code for uploading files to Drive</h2>
<p>The below code shows the landing page interface in HTML and the JavaScript asset created for <a href="https://phppot.com/php/working-on-file-upload-using-php/">uploading the files</a> to Google Drive.</p>
<h3>HTML code to display controls for requesting authorization and upload</h3>
<p>When landing on the home page, it displays an&nbsp;<em>Authorize</em> button in the UI. On clicking this button, it shows the Google sign-in <a href="https://phppot.com/php/add-edit-comments-using-jquery-dialogify/">overlay dialog</a> to proceed with the authorization request.</p>
<p>In this step, the user must prove their identity to have access to upload to the Drive directory.</p>
<p class="code-heading">index.php</p>
<pre class="prettyprint"><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Google Drive upload using JavaScript&lt;/title&gt;
&lt;meta charset="utf-8" /&gt;
&lt;meta name="viewport" content="width=device-width, initial-scale=1" /&gt;
&lt;link rel="stylesheet" type="text/css" href="css/style.css" /&gt;
&lt;link rel="stylesheet" type="text/css" href="css/form.css" /&gt;
&lt;style&gt;
#content { display: none;
}
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt; &lt;!--Add HTML buttons to sign in and sign out--&gt; &lt;div class="phppot-container"&gt; &lt;h1&gt;Google Drive upload using JavaScript&lt;/h1&gt; &lt;div&gt; &lt;div class="row"&gt; &lt;input type="button" id="authorize_button" onclick="handleAuthClick()" value="Authorize"&gt; &lt;input type="button" id="signout_button" onclick="handleSignoutClick()" value="Sign Out"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="content" class="success message"&gt;&lt;?php if(isset($message)) { echo $message; } ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;script type="text/javascript" src="./js/gapi-upload.js"&gt;&lt;/script&gt; &lt;script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"&gt;&lt;/script&gt; &lt;script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h2>JavaScript to handle user authorization and file upload sequence</h2>
<p>This JavaScript code initializes the <em>gapi</em> and <em>gsi</em> on a callback of loading these Google JavaScript libraries.</p>
<p>It also contains the handlers to trigger API requests for the following actions.</p>
<ol>
<li>Google authorization with identity proof.</li>
<li>Upload files with the access token.</li>
<li>Refresh <em>gapi</em> upload action once authorized.</li>
<li>Signout.</li>
</ol>
<p>This JavaScript code requires the authorization credentials to be configured. Set the CLIENT_ID and API_KEY in this script before running this example.</p>
<p>In this example, it sets the Google Drive folder id to upload the file via JavaScript. This configuration is optional. If no target is needed, remove the parameter from the file meta array.</p>
<p class="code-heading">js/gapi-upload.js</p>
<pre class="prettyprint"><code class="language-javascript">// TODO: Set the below credentials
const CLIENT_ID = 'SET-YOUR-CLIENT-ID';
const API_KEY = 'SET-YOUR-API-KEY'; // Discovery URL for APIs used by the quickstart
const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'; // Set API access scope before proceeding authorization request
const SCOPES = 'https://www.googleapis.com/auth/drive.file';
let tokenClient;
let gapiInited = false;
let gisInited = false; document.getElementById('authorize_button').style.visibility = 'hidden';
document.getElementById('signout_button').style.visibility = 'hidden'; /** * Callback after api.js is loaded. */
function gapiLoaded() { gapi.load('client', initializeGapiClient);
} /** * Callback after the API client is loaded. Loads the * discovery doc to initialize the API. */
async function initializeGapiClient() { await gapi.client.init({ apiKey: API_KEY, discoveryDocs: [DISCOVERY_DOC], }); gapiInited = true; maybeEnableButtons();
} /** * Callback after Google Identity Services are loaded. */
function gisLoaded() { tokenClient = google.accounts.oauth2.initTokenClient({ client_id: CLIENT_ID, scope: SCOPES, callback: '', // defined later }); gisInited = true; maybeEnableButtons();
} /** * Enables user interaction after all libraries are loaded. */
function maybeEnableButtons() { if (gapiInited &amp;&amp; gisInited) { document.getElementById('authorize_button').style.visibility = 'visible'; }
} /** * Sign in the user upon button click. */
function handleAuthClick() { tokenClient.callback = async (resp) =&gt; { if (resp.error !== undefined) { throw (resp); } document.getElementById('signout_button').style.visibility = 'visible'; document.getElementById('authorize_button').value = 'Refresh'; await uploadFile(); }; if (gapi.client.getToken() === null) { // Prompt the user to select a Google Account and ask for consent to share their data // when establishing a new session. tokenClient.requestAccessToken({ prompt: 'consent' }); } else { // Skip display of account chooser and consent dialog for an existing session. tokenClient.requestAccessToken({ prompt: '' }); }
} /** * Sign out the user upon button click. */
function handleSignoutClick() { const token = gapi.client.getToken(); if (token !== null) { google.accounts.oauth2.revoke(token.access_token); gapi.client.setToken(''); document.getElementById('content').style.display = 'none'; document.getElementById('content').innerHTML = ''; document.getElementById('authorize_button').value = 'Authorize'; document.getElementById('signout_button').style.visibility = 'hidden'; }
} /** * Upload file to Google Drive. */
async function uploadFile() { var fileContent = 'Hello World'; // As a sample, upload a text file. var file = new Blob([fileContent], { type: 'text/plain' }); var metadata = { 'name': 'sample-file-via-js', // Filename at Google Drive 'mimeType': 'text/plain', // mimeType at Google Drive // TODO [Optional]: Set the below credentials // Note: remove this parameter, if no target is needed 'parents': ['SET-GOOGLE-DRIVE-FOLDER-ID'], // Folder ID at Google Drive which is optional }; var accessToken = gapi.auth.getToken().access_token; // Here gapi is used for retrieving the access token. var form = new FormData(); form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' })); form.append('file', file); var xhr = new XMLHttpRequest(); xhr.open('post', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&amp;fields=id'); xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken); xhr.responseType = 'json'; xhr.onload = () =&gt; { document.getElementById('content').innerHTML = "File uploaded successfully. The Google Drive file id is &lt;b&gt;" + xhr.response.id + "&lt;/b&gt;"; document.getElementById('content').style.display = 'block'; }; xhr.send(form);
}
</code></pre>
<h2>Google Drive JavaScript Upload Response</h2>
<p>Once authorized, the JavaScript calls the <em>uploadFile()</em> function to hit the Google Drive V3 API to post the file binary.</p>
<p>The below screenshot shows the uploaded Google Drive file id in the success message.</p>
<p>After sign-in, the landing page UI will <a href="https://phppot.com/wordpress/how-to-force-logout-all-users-from-wordpress-site/">display the signout option</a>. It also shows a&nbsp;<em>Refresh</em> button to trigger upload action again in case of any issues on uploading.</p>
<p><img loading="lazy" class="alignnone size-large wp-image-18947" src="https://phppot.com/wp-content/uploads/2022/08/file-upload-ack-with-google-drive-file-id-550x136.jpg" alt="file upload ack with google drive file id" width="550" height="136" srcset="https://phppot.com/wp-content/uploads/2022/08/file-upload-ack-with-google-drive-file-id-550x136.jpg 550w, https://phppot.com/wp-content/uploads/20...300x74.jpg 300w, https://phppot.com/wp-content/uploads/20...ile-id.jpg 600w" sizes="(max-width: 550px) 100vw, 550px"><br /><a class="download" href="https://phppot.com/downloads/javascript/google-drive-upload-javascript.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/javascript/google-drive-upload-javascript/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2022/08/...avascript/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016