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);
}
};
}());
@Daniel15
Copy link
Author

I created this example a long time ago and I'm not sure if some changes are required to update it to Google's newer APIs... That could be why it's not working.

@KrishnaDhakate
Copy link

@Daniel15 This code is working for me but sometime later it stops working and after a week gets starts. What can be the issue?
`var file = null;
function initPicker() {
var picker = new FilePicker({

			apiKey: 'XXXXXXXXXXXDM2vYIPN_XwuD8B2HhLyc',
	          clientId:'XXXXXXX-gkrnjl6oXXXXXXXXXXXX.apps.googleusercontent.com',
			buttonEl: document.getElementById('pick'),
			
			onSelect: function(file) {
				
				$("#filename").val(file.title);
				$(".file-upload-input").val(file.title);
				$("#fileId").val(file.id);
				console.log(file);
				document.getElementById("save").click();
				
			}
		});	
		$("#pick").on('click', function () {
		    $(this).tooltip('hide');
		  });
		
	}`

FilePicker.js
`(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).
			addView(google.picker.ViewId.PDFS).
			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:'XXXXXX-gkrnjl6o6akimXXXX.apps.googleusercontent.com',
			scope: 'https://www.googleapis.com/auth/drive',
			immediate: immediate,
			redirect_uri: 'postmessage'
		}, callback);
	}
};

}());
`

error:
loader.js?key=XXXXXXXXXOGf547C0XifZ0HagRx64w:94
Uncaught Error: Module "picker" is not supported.
at loader.js?key=XXXXXXXXXOGf547C0XifZ0HagRx64w:94

@KrishnaDhakate
Copy link

I have replaced one line from filepicker.js and its working now.
replaced
google.load('picker', '1', { callback: this._pickerApiLoaded.bind(this) });
with
gapi.load('picker', {'callback': this._pickerApiLoaded.bind(this)});

@menantisenja
Copy link

Hi please help me

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

@KrishnaDhakate
Copy link

KrishnaDhakate commented Dec 29, 2020

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

@JLarky
Copy link

JLarky commented Jun 20, 2021

I have fork with updated ClientId handling and better picker (allows to open folders) https://gist.github.com/JLarky/640859bed8704520dd61

I updated my fork with gapi.load(picker, fix

@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?

@ajith-acumen
Copy link

any flutter sample code

@Naveen-mergerware
Copy link

Hello,

Can any one help me with code for Google Drive File picker in MeteorJs

@AnusreeAnavathukkal
Copy link

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

@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