Skip to content

Instantly share code, notes, and snippets.

@JLarky
Forked from Daniel15/1_README.md
Last active January 19, 2022 22:35
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save JLarky/640859bed8704520dd61 to your computer and use it in GitHub Desktop.
Save JLarky/640859bed8704520dd61 to your computer and use it in GitHub Desktop.

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_CLIENT_ID_HERE with 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) 2014 Yaroslav Lapin (JLarky) 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>
<pre id="fileInfo"></pre>
<script src="filepicker4.js"></script>
<script>
function initPicker() {
var picker = new FilePicker({
apiKey: 'PUT_YOUR_API_KEY_HERE',
clientId: 'PUT_YOUR_CLIENT_ID_HERE',
buttonEl: document.getElementById('pick'),
onSelect: function(file) {
console.log(file);
document.getElementById('fileInfo').innerHTML = file.title + '\n' + file.alternateLink;
}
});
}
</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));
gapi.load('picker', {'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;
var view = new google.picker.DocsView();
view.setIncludeFolders(true);
this.picker = new google.picker.PickerBuilder()
.enableFeature(google.picker.Feature.NAV_HIDDEN)
.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
.setAppId(this.clientId)
.setDeveloperKey(this.apiKey)
.setOAuthToken(accessToken)
.addView(view)
.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,
scope: 'https://www.googleapis.com/auth/drive.readonly',
immediate: immediate
}, callback);
}
};
}());
@tubyeipyaj
Copy link

Hi, can you lend me a help regards on running the google picker in google appscript? I tried doing it by using the code above but it's not working.

Thanks and Best Regards,

@totoprayogo1916
Copy link

Thanks, it's work

@pu3antasyah
Copy link

result is

"undefined
undefined"

for document.getElementById('fileInfo').innerHTML = file.title + '\n' + file.alternateLink;

@elliotsoomro
Copy link

elliotsoomro commented Dec 12, 2017

@pu3antasyah I had the same problem as you. To solve it, enable the Google Drive API for the project, then wait a few minutes. There should be a link in the console directing you to where this can be done. Otherwise, visit https://console.developers.google.com/apis/api/drive.googleapis.com/overview

@menantisenja
Copy link

Hi please help me

I'm using your js, but i'm getting error "Uncaught Error: Module "picker" is not supported."

@marianogo
Copy link

same as @menantisenja

@JLarky
Copy link
Author

JLarky commented Jun 9, 2021

I haven't touched this code since 2014 :) if someone knows how to fix it, please contact me :)

@Suppenhuhn79
Copy link

Replace google.load('picker', '1', { callback: this._pickerApiLoaded.bind(this) });
with gapi.load('picker', {'callback': this._pickerApiLoaded.bind(this)});

@JLarky
Copy link
Author

JLarky commented Jun 20, 2021

@Suppenhuhn79 thank you for this!

@Andy-91
Copy link

Andy-91 commented Sep 14, 2021

Google made a security update on the September 13, 2021 and this no longer works at all. It is something to do with the resource key of a file or folder with the getResourceKey method.

Anybody got clue what needs to be updated?

@Suppenhuhn79
Copy link

I do not encounter any issues. For me everything works as usual. But I do not use a getResourceKey method...

What do you mean by "this no longer works at all"? What response or error do you get?

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