Skip to content

Instantly share code, notes, and snippets.

@Daniel15
Last active November 7, 2024 19:51
Show Gist options
  • Save Daniel15/5994054 to your computer and use it in GitHub Desktop.
Save Daniel15/5994054 to your computer and use it in GitHub Desktop.
Complete Google Drive File Picker example

Google Drive File Picker Example

This is an example of how to use the Google Drive file picker and Google Drive API to retrieve files from Google Drive using pure JavaScript. At the time of writing (14th July 2013), Google have good examples for using these two APIs separately, but no documentation on using them together.

Note that this is just sample code, designed to be concise to demonstrate the API. In a production environment, you should include more error handling.

See a demo at http://stuff.dan.cx/js/filepicker/google/

Usage

  1. Get a Google Drive API key (refer to Google's Quickstart guide for instructions).
  2. Replace PUT_YOUR_API_KEY_HERE with your API key (listed under "Key for browser apps" in Google's API console)
  3. Replace PUT_YOUR_NUMERIC_CLIENT_ID_HERE with the numeric portion of your OAuth2 client ID (xxxxxxxxxx.apps.googleusercontent.com)
  4. Test out the code to ensure it works
  5. Replcae the onSelect method with your own code

References

Licence

(The MIT licence)

Copyright (C) 2013 Daniel Lo Nigro (Daniel15)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Google Drive File Picker Example</title>
</head>
<body>
<button type="button" id="pick">Pick File</button>
<script src="filepicker.js"></script>
<script>
function initPicker() {
var picker = new FilePicker({
apiKey: 'PUT_YOUR_API_KEY_HERE',
clientId: PUT_YOUR_NUMERIC_CLIENT_ID_HERE,
buttonEl: document.getElementById('pick'),
onSelect: function(file) {
console.log(file);
alert('Selected ' + file.title);
}
});
}
</script>
<script src="https://www.google.com/jsapi?key=PUT_YOUR_API_KEY_HERE"></script>
<script src="https://apis.google.com/js/client.js?onload=initPicker"></script>
</body>
</html>
/**!
* Google Drive File Picker Example
* By Daniel Lo Nigro (http://dan.cx/)
*/
(function() {
/**
* Initialise a Google Driver file picker
*/
var FilePicker = window.FilePicker = function(options) {
// Config
this.apiKey = options.apiKey;
this.clientId = options.clientId;
// Elements
this.buttonEl = options.buttonEl;
// Events
this.onSelect = options.onSelect;
this.buttonEl.addEventListener('click', this.open.bind(this));
// Disable the button until the API loads, as it won't work properly until then.
this.buttonEl.disabled = true;
// Load the drive API
gapi.client.setApiKey(this.apiKey);
gapi.client.load('drive', 'v2', this._driveApiLoaded.bind(this));
google.load('picker', '1', { callback: this._pickerApiLoaded.bind(this) });
}
FilePicker.prototype = {
/**
* Open the file picker.
*/
open: function() {
// Check if the user has already authenticated
var token = gapi.auth.getToken();
if (token) {
this._showPicker();
} else {
// The user has not yet authenticated with Google
// We need to do the authentication before displaying the Drive picker.
this._doAuth(false, function() { this._showPicker(); }.bind(this));
}
},
/**
* Show the file picker once authentication has been done.
* @private
*/
_showPicker: function() {
var accessToken = gapi.auth.getToken().access_token;
this.picker = new google.picker.PickerBuilder().
addView(google.picker.ViewId.DOCUMENTS).
setAppId(this.clientId).
setOAuthToken(accessToken).
setCallback(this._pickerCallback.bind(this)).
build().
setVisible(true);
},
/**
* Called when a file has been selected in the Google Drive file picker.
* @private
*/
_pickerCallback: function(data) {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var file = data[google.picker.Response.DOCUMENTS][0],
id = file[google.picker.Document.ID],
request = gapi.client.drive.files.get({
fileId: id
});
request.execute(this._fileGetCallback.bind(this));
}
},
/**
* Called when file details have been retrieved from Google Drive.
* @private
*/
_fileGetCallback: function(file) {
if (this.onSelect) {
this.onSelect(file);
}
},
/**
* Called when the Google Drive file picker API has finished loading.
* @private
*/
_pickerApiLoaded: function() {
this.buttonEl.disabled = false;
},
/**
* Called when the Google Drive API has finished loading.
* @private
*/
_driveApiLoaded: function() {
this._doAuth(true);
},
/**
* Authenticate with Google Drive via the Google JavaScript API.
* @private
*/
_doAuth: function(immediate, callback) {
gapi.auth.authorize({
client_id: this.clientId + '.apps.googleusercontent.com',
scope: 'https://www.googleapis.com/auth/drive.readonly',
immediate: immediate
}, callback);
}
};
}());
@V-Ramachandiran
Copy link

V-Ramachandiran commented Apr 27, 2023

access token get an null what to do

		var token = gapi.auth.getToken();
		if (token) {
			this._showPicker();
		} else {
			// The user has not yet authenticated with Google
			// We need to do the authentication before displaying the Drive picker.
			this._doAuth(false, function() { this._showPicker(); }.bind(this));
		}

@Sivamani-18
Copy link

Sivamani-18 commented Jul 4, 2023

Can someone please help with Google picker version 2 (Onepick) sample to upload file to a specified folder in drive? Thanks in advance.

https://www.npmjs.com/package/google-drive-picker

Try This NPM Package it is working on setParentFolder

@mhedadji
Copy link

mhedadji commented Jan 7, 2024

A bit of a shot in the dark, but hoping someone with experience here can help clarify the true function of the picker API for me & my team. We were able to successfully implement the Picker API, but its true function seems to be just a UX to more easily pick files.

Our app is seeking to oAuth into a user's file (specifically GSheet), where we'll upload data each day on a schedule. The Google Verification team suggested the Picker API and drive.file scope in order to do so, but we're unable to successfully gain permissions to the file in question, to actually edit the contents of the file (by writing data to one of the tabs, and/or creating new tabs in the Gsheet).

If anyone has advice on how to leverage the drive.file scope and Picker API to gain access to a file, and update/edit that file, it would be a massive help. Otherwise, if that's truly not the function of this scope, it would be equally valuable to know that definitively. Thank you, in advance!

@zspotter
Copy link

@mhedadji I'm dealing with the same issue now, and google's support isn't able to give a clear answer to us. If you're working with spreadsheets only, you might be able to use the https://www.googleapis.com/auth/spreadsheets scope, which gives RW access to all sheets. It's a "sensitive" scope but the verification requirements are much simpler than restricted scopes like https://www.googleapis.com/auth/drive.readonly

@author-spirit
Copy link

This thread is very helpful.
Helped me to successfully apply several actions.
@omarwagih Thanks for oncancel event.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment