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

ghost commented Jul 3, 2017

Implemented the google picker and getting corrupted images in the drive but able to use all the images and videos

screenshot from 2017-07-02 18-21-27

@SHAIKINTHIYAZALI
Copy link

hi anybody help me to see the google drive images in ui

@doananhbao94
Copy link

Hi sir,
Can you help me setting this can using in localhost angular-cli?
I always have this problem:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://docs.google.com') does not match the recipient window's origin ('http://localhost:1337').
Invalid 'X-Frame-Options' header encountered when loading 'https://docs.google.com/picker?protocol=gadgets&origin=http%3A%2F%2Flocalho…(%22all%22))&rpctoken=ln6puug03gm7&rpcService=e0we9gysr74e&thirdParty=true': 'ALLOW-FROM http://localhost:1337' is not a recognized directive. The header will be ignored.

Please help me fast as you can.
Thank you so much.

@kota65535
Copy link

kota65535 commented Jul 30, 2017

I found that the following error messages appear in console when clicking the "Pick File" button of the demo page above.

with Google Chrome:

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://docs.google.com') does not match the recipient window's origin ('http://stuff.dan.cx').
Invalid 'X-Frame-Options' header encountered when loading 'https://docs.google.com/picker?protocol=gadgets&origin=http%3A%2F%2Fstuff.d…cuments%22))&rpctoken=e22a74euhgrw&rpcService=trqzzcae8255&thirdParty=true': 'ALLOW-FROM http://stuff.dan.cx' is not a recognized directive. The header will be ignored.

with Safari:

Unable to post message to https://docs.google.com. Recipient has origin http://stuff.dan.cx.
Invalid 'X-Frame-Options' header encountered when loading 'https://docs.google.com/picker?protocol=gadgets&origin=http%3A%2F%2Fstuff.dan.cx&oauth_token=ya29.GluYBEZ9m_UnTUuqeW1MSHsFT-4z0TbAYCbbXoETvkC1bIQ3WwfTY_8OWanSLB1aP5NUp6CGKC8YarcPJHVvNdyVvofeVAfW7mhEFWI3tvnANg-pDN2Gg5k87DPE&hostId=stuff.dan.cx&relayUrl=http%3A%2F%2Fstuff.dan.cx%2Ffavicon.ico&nav=((%22documents%22))&rpctoken=x0kwinaagzwk&rpcService=wyhneeduqhtc&thirdParty=true': 'ALLOW-FROM http://stuff.dan.cx' is not a recognized directive. The header will be ignored.

Is there something wrong?

@samuelvi
Copy link

samuelvi commented Aug 21, 2017

I use this code to download a binary image from drive using google picker. The trick part is in xhr.responseType = 'blob';

var xhr = new XMLHttpRequest();
xhr.open('GET', THE_PREVIOUSLY_GOTTEN_DOWNLOAD_URL);
xhr.setRequestHeader('Authorization', 'Bearer ' + THE_OBTAINED_OAUTHTOKEN);
xhr.responseType = 'blob';
xhr.onload = function () {
  
   // Better trigger and event and manage the response outside the onload function. For demo purposes:
   $('#THE_IMG_ID').attr( 'src', URL.createObjectURL(xhr.response) );
};
xhr.onerror = function () {
};
xhr.send();

@Mayuresh0
Copy link

Hello:

I am uploading file using Drive API. The file is getting uploaded successfully and I can open it on Drive. But when I try to download it manually nothing is getting downloaded. It just redirects to blank screen on new tab. Here is my code.

Step ONE : Creating blank file on the drive

String fileID  = null;
 private void CreateFile()
{
	File f_GoogleFile         = new File();
	f_GoogleFile.Title        =  _fileName;
	f_GoogleFile.MimeType     = _MimeType;
	var _insertRequest        = DriveService.Files.Insert(f_GoogleFile);

	f_GoogleFile = f_InsertReq.Execute();
	fileID = f_GoogleFile.Id;
}

Step TWO: Uploading data using HTTPWbrequest

private void UploadDataRequest()
{
	String UploadUrl = null;
	HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(p_RequestUri);
    httpRequest.Headers["Authorization"] = "Bearer " + p_AccessToken;
    httpRequest.Method = "PUT";	
				
	using (Stream f_ReqStream = httpRequest.GetRequestStream())
	{ }
	
	using (HttpWebResponse f_ObjWebResponse = (HttpWebResponse)httpRequest.GetResponse())
	{
		if (f_ObjWebResponse.StatusCode == HttpStatusCode.OK)
		{
			UploadUrl = f_ObjWebResponse.Headers["Location"].ToString();
		}
	}
	
	
    HttpWebRequest uploadRequest  = (HttpWebRequest)WebRequest.Create(UploadUrl);
    
     uploadRequest.Method         = "PUT";               

     uploadRequest.ContentLength  = fileBytesArray.Length;
			
     using (Stream f_ObjHttpStream = uploadRequest.GetRequestStream())
     {
         MemoryStream f_ChunkStream = null;

         f_ChunkStream = new MemoryStream(fileBytesArray);

         f_ChunkStream.CopyTo(f_ObjHttpStream);                   

         f_ObjHttpStream.Flush();

         f_ObjHttpStream.Close();

         f_ChunkStream.Close();

     }
     
  using (HttpWebResponse httpResponse = (HttpWebResponse)(uploadRequest.GetResponse()))
      {

      if (httpResponse.StatusCode == HttpStatusCode.OK)
          {
          p_RetryCount = 0;

          httpResponse.Close();

          return f_IsUploaded = true;
          }
      }
}

Any help on this is greatly appreciated.

Thank you.

@robinbhu
Copy link

robinbhu commented Jan 2, 2018

How can i use this with angular4 ?
Please Help

@roydekleijn
Copy link

How to use with Angular 5 / typescript?

@nikuraj006
Copy link

image
i got this error how it solve

@Rajesh3646
Copy link

Good to see example demonstrating file picker. I tested it in chrome and its working fine. However, It seems to be not working in Internet explorer.

Problem:
After clicking Agree on Google window, Google window is getting vanished and picker is not coming up. I observed console error as below:

image

@qayyumabro
Copy link

Replace this

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));

with:

var files = data[google.picker.Response.DOCUMENTS];
// loop over selected files 
for (var i = 0; i < files.length; i++) {
    // get file id, and request to get the file
    var id = files[i][google.picker.Document.ID],
        request = gapi.client.drive.files.get({
            fileId: id
        });
    // execute request for file 
    request.execute(this._fileGetCallback.bind(this));
}

And add this line after this.picker = new google.picker.PickerBuilder(). to enable multiple file selection
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).

@steinhaug
Copy link

Well, I tried this and could not get it to work :( I believe I did all the credentials correct, and applied all the knowledge from this thread aswell but it didnt work. :(

Screenshot from the network tab in developer tools:

@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