Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
}
};
}());
@dlgresults

This comment has been minimized.

Copy link

commented Jan 15, 2014

This gives you the web link for the file but you cannot download the actual file to the server. Do you have a method to do that?

@altfuns

This comment has been minimized.

Copy link

commented Feb 27, 2014

Thank you for share this example. It works great and out of the box!

The view type, locale and mime type can be in the options parameters.

@BedouiMouoifek

This comment has been minimized.

Copy link

commented Apr 20, 2014

so how to download file via googledrive and javasctipt

@chandugsi

This comment has been minimized.

Copy link

commented May 1, 2014

it works fine in firefox and chrome but not in IE 9 or 10 or 11 in compatibility mode....... i need to run this code in ie compatibility please give me a code for run in IE compatibility

@g5li

This comment has been minimized.

Copy link

commented May 31, 2014

Replace PUT_YOUR_NUMERIC_CLIENT_ID_HERE with the numeric portion of your OAuth2 client ID (xxxxxxxxxx.apps.googleusercontent.com)

at new google developer console , the client ID is not numberic, it's string such like
458068379722-ahome509igjdqi62oa8io7mcrip2vg09

@jadaun011

This comment has been minimized.

Copy link

commented Jun 11, 2014

Can Anyone tell me ,...how to move file from googledrive to my own server?

@juanghurtado

This comment has been minimized.

Copy link

commented Jun 20, 2014

To download the selected file with JS, use this:

function downloadFile(file, callback) {
  if (file.downloadUrl) {
    var accessToken = gapi.auth.getToken().access_token;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file.downloadUrl);
    xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
    xhr.onload = function() {
      callback(xhr.responseText);
    };
    xhr.onerror = function() {
      callback(null);
    };
    xhr.send();
  } else {
    callback(null);
  }
}

Seen in the examples here: https://developers.google.com/drive/web/manage-downloads

@hectolec

This comment has been minimized.

Copy link

commented Jun 26, 2014

Im having this issue "Error: invalid_client no registered origin", i searched this error and its supposed to be shown when redirect uri and javasript origin are wrong , but with another example for uploading it works just fine

@JLarky

This comment has been minimized.

Copy link

commented Sep 11, 2014

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

@tubyeipyaj

This comment has been minimized.

Copy link

commented Sep 24, 2014

Hi all, 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,

@onesolution4many

This comment has been minimized.

Copy link

commented Oct 20, 2014

Hi all, any one can help me to save the file content to my server using javascript ? I am using
function downloadFile(file, callback) {
if (file.downloadUrl) {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', file.downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
callback(xhr.responseText);
};
xhr.onerror = function() {
callback(null);
};
xhr.send();
} else {
callback(null);
}
}
to get file content but I am unable to save the file into my server. any one can help me to save file using php or javascript?

@Daniel15

This comment has been minimized.

Copy link
Owner Author

commented Oct 25, 2014

@dlgresults You send the URL of the selected file to the server, and then the server can download it (it has an auth token in the URL that expires after a while)

@justinedehonor

This comment has been minimized.

Copy link

commented Nov 10, 2014

I've got an error:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').

@alexjamesbrown

This comment has been minimized.

Copy link

commented Jan 21, 2015

Every time my modal window opens, it immediately shuts again - any idea what could be causing this?

@bradvogel

This comment has been minimized.

Copy link

commented Mar 3, 2015

Anyone able to pass a login_hint to gapi.auth.authorize? E.g.

gapi.auth.authorize({
    login_hint: 'myemail@mixmax.com'
});
@Daniel15

This comment has been minimized.

Copy link
Owner Author

commented May 17, 2015

@justinedehonor - Try loading the page from a http or https URL rather than a local file.

@harrysileoni

This comment has been minimized.

Copy link

commented Jul 30, 2015

The picker seems to work, but when I select a file, it never gives the alert message. When I checked this with the JavaSript Console, I get the following error:

Uncaught TypeError: Cannot read property 'files' of undefined
FilePicker._pickerCallback @ filepicker.js:69
K.ae @ default.I.js:107
g @ cb=gapi.loaded_0:86
c @ cb=gapi.loaded_0:77

Anyone know what could be wrong?

@aaesis

This comment has been minimized.

Copy link

commented Nov 4, 2015

hi I have a weird issue. Please advise. only my image thumbnails are corrupted. Do you have any solution?

screenshot
ease.

@tomasreichmann

This comment has been minimized.

Copy link

commented Nov 12, 2015

I am getting an error:
cb=gapi.loaded_0:41 Uncaught null

http://codepen.io/tomasreichmann/pen/XmoXXa

@davidduran

This comment has been minimized.

Copy link

commented Jan 11, 2016

@alexjamesbrown

Did you ever get a resolution for this:
alexjamesbrown commented on Jan 21, 2015
Every time my modal window opens, it immediately shuts again - any idea what could be causing this?

I have the same issue.

@trf000

This comment has been minimized.

Copy link

commented Jan 15, 2016

How would i get the url of the document and then place that in a textbox or textarea? And is it possible to select multiple items?

@trf000

This comment has been minimized.

Copy link

commented Jan 15, 2016

@tomasreichmann the problem is your client id. only use the numeric portion before the dash. select the rest and place it in filepicker.js at line 108 before .apps.googleusercontent.com

That said, when i select a file I get an error saying Selected undefined

Edit: ugh, wrong api key.

So i get the alert with the file title. I need the url displayed in a textbox. but i'm getting no alert when i try to change from ID to URL

@wishwa

This comment has been minimized.

Copy link

commented Feb 4, 2016

hi I'm using following code to download files from Google Drive but when I downloaded the file is corrupted. Any body have idea why file is getting corrupted ?

function downloadGDriveFile() {
alert(1);
var id = 'FILEID';
var downloadUrl = 'https://www.googleapis.com/drive/v2/files/'+ id+'?alt=media';
var accessToken = MYTOKEN;
var mType = 'image/jpeg';
var name = 'Internet_of_Things.jpg';

if (downloadUrl) {
  alert(2);
  var xhr = new XMLHttpRequest();
  xhr.open('GET', downloadUrl);
  xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
  xhr.onload = function() {
    alert(xhr.responseType);
    alert(xhr.response);
    downloadFile(xhr.responseText);
  };
  xhr.onerror = function() {
    downloadFile(null);
  };
  xhr.send();
}

else {
  alert("Unable to download file.");
}

}

function downloadFile(data){
var name = 'Internet_of_Things.jpg';
var a = document.createElement("a");
a.style = "display: none";
var json = data,
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
}

downloadGDriveFile();

@kylepapili

This comment has been minimized.

Copy link

commented Feb 27, 2016

Using this example, is there anyway to retrieve the shareable URL from the selected document. What I want to do is retrieve the URL that will allow other people who are NOT signed in to view the document. I did not see that URL anywhere in the returned object, is there anyway to retrieve that?

THANKS!

@ValentinTSM

This comment has been minimized.

Copy link

commented Mar 1, 2016

Hey,

Thank you for sharing your code!
I was just wondering as I found a post from you working on including a file from Cloud Providers (Dropbox/Google drive/Linkedin) if by any chance you knew a library that can do everything so we don't have to code for every provider?

Thanks

@rohitweb007

This comment has been minimized.

Copy link

commented Mar 8, 2016

Hi, I could not download a file... getting binary file..

function downloadFileView(data, name, mimeType) {
var a = document.createElement("a");
a.style = "display: none";
var json = data,
blob = new Blob([json], {type: mimeType}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
}

function downloadFile(file, tokenKey) {
    //var downloadUrl = 'https://www.googleapis.com/drive/v2/files/' + file.id + '?alt=media';
    var downloadUrl = file.downloadUrl;

    if (downloadUrl) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', downloadUrl);
        xhr.setRequestHeader('Authorization', 'Bearer ' + tokenKey);
        xhr.onload = function() {
            alert(xhr.responseText);
            downloadFileView(xhr.responseText, file.title, file.mimeType);
        };
        xhr.onerror = function() {
            downloadFile(null);
        };
        xhr.send();
    }

    else {
        alert("Unable to download file.");
    }
}
@omarwagih

This comment has been minimized.

Copy link

commented Apr 12, 2016

Thanks for this! Really helps. It would also make sense to implement onCancel under _pickerCallback

if(data[google.picker.Response.ACTION] == google.picker.Action.CANCEL){ this._fileGetCallback(null); }

For when the cancel button is hit.

@kurianbenny

This comment has been minimized.

Copy link

commented Apr 28, 2016

I get only documents from my drive. Help me to change the scope to whole drive @Daniel15

@kurianbenny

This comment has been minimized.

Copy link

commented Apr 28, 2016

Downloaded files are corrupted. please help me to find a solution

@jaganraj1

This comment has been minimized.

Copy link

commented Jan 11, 2017

Hi I can able to view the documents in the pop up,I need to view the selected document from the drive in a separate page and edit the document and upload.is that possible using this script?

@trf000

This comment has been minimized.

Copy link

commented Jan 13, 2017

So, apparently google made a change since I installed this. In the version I installed, Jan 2015, I was able to browse folders to find any files. Now every folder say it is empty. The new version looks for any documents (only) regardless of folder. Uploaded PDF's are not included.

Which, for me, is a problem.

Why is folder browsing no longer supported? How do I include PDF's and other media?

@trf000

This comment has been minimized.

Copy link

commented Jan 13, 2017

@kurianbenny

Change line 53 from

ViewId.DOCUMENTS

to

ViewId.DOCS

That covers everything Drive holds.

@trf000

This comment has been minimized.

Copy link

commented Jan 13, 2017

@kylexy32

              //					alert('Selected ' + file.id);
              			var TheTextBox = document.getElementById("file_address");
              		    TheTextBox.value = TheTextBox.value + "https://drive.google.com/open?id=" +file.id;

then you can get the output in any element with an id of file_address

@sagarsoni168

This comment has been minimized.

Copy link

commented Feb 2, 2017

picking google docs from google to my application is works for me.now i want to upload files on google documents from my application to google docs.

for example, if i attach any file in my application attachment same file is created on google documents and i want to access all my documents from google docs

can anyone suggest me how i can able to do this

@creedrahul

This comment has been minimized.

Copy link

commented Feb 16, 2017

If anyone wants to download a file from google drive you will have to change the scope of access that is defined in filepicker.js in _doAuth the current scope is set as : https://www.googleapis.com/auth/drive.readonly this need to be https://www.googleapis.com/auth/drive once this is done users will be able to download file using the following code

function downloadGDriveFile (file) {
if (file.downloadUrl) {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', file.downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
var content = xhr.responseText;
do_something_with_file_content(file.title, content);
};
xhr.onerror = function() {
alert('Download failure.');
};
xhr.send();
}
else {
alert('Unable to download file.');
}
}

just send the file object to the above function .

@rifaldhiaw

This comment has been minimized.

Copy link

commented Feb 19, 2017

Sorry for little OOT.
anybody know how to make it become responsive? I mean like on slack, the google drive extension is responsive and can be used on mobile web. Thanks

@LimeBlast

This comment has been minimized.

Copy link

commented Mar 22, 2017

@creedrahul thank you for your code sample, I was hoping you might be able to expand upon it a little for me, please? Specifically, I'm interested in what the do_something_with_file_content() function might contain.

For my own part, I'm looking to let someone upload a file from Google Drive into a Rails app (using Carrierwave), and as such, already have a browse files button as part of the form. Would it be possible to use the content data to attach the file to the browse button, so when they hit submit, it acts like a regular upload would?

@prachi708

This comment has been minimized.

Copy link

commented Mar 27, 2017

I am able to reterive url of picker box in my console using picker.build() but when i am trying to do same in code it is showing error on picker.setVisible() . I am using meteor to build my project. Any help for how to display picker box will be appreciated.

@Sharma-Ravin

This comment has been minimized.

Copy link

commented Apr 19, 2017

how to fire a event on cancel button. On file picker resulting popup.

@Manohartk

This comment has been minimized.

Copy link

commented Jun 8, 2017

Thankx Working Great!..

@muralitharanvellaisamy

This comment has been minimized.

Copy link

commented Jun 8, 2017

Oh! Great Man. It useful for me. Thanks.....
clientId: PUT_YOUR_NUMERIC_CLIENT_ID_HERE,
use Instead of
clientID: 'Use OAuth2 client ID',

@etyp

This comment has been minimized.

Copy link

commented Jun 17, 2017

@prachi708 what errors are you getting, specifically?

We've had gap.load('picker', { ... }); in for months and it just recently broke, throwing the following error:

api.js:11 Uncaught TypeError: _.Rp is not a function
    at https://apis.google.com/_/scs/apps-static/_/js/k=oz.gapi.en.npUTEjvGP7I.O/m…=1/ed=1/am=AQ/rs=AGLTcCO-cN8Rg66fl-34jwiyTEAP1SGPAA/cb=gapi.loaded_1:8:501
    at https://apis.google.com/js/api.js:8:214
    at X (https://apis.google.com/js/api.js:11:220)
    at qa (https://apis.google.com/js/api.js:8:154)
    at W (https://apis.google.com/js/api.js:10:155)
    at b (https://apis.google.com/js/api.js:10:381)
    at Array.Y.r.(anonymous function) (https://apis.google.com/js/api.js:10:485)
    at Object.Y.x.(anonymous function) [as loaded_1] (https://apis.google.com/js/api.js:11:38)
    at https://apis.google.com/_/scs/apps-static/_/js/k=oz.gapi.en.npUTEjvGP7I.O/m…d=1/ed=1/am=AQ/rs=AGLTcCO-cN8Rg66fl-34jwiyTEAP1SGPAA/cb=gapi.loaded_1:1:15

Is anybody else getting this?

@sbsomya

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented Jul 17, 2017

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

@doananhbao94

This comment has been minimized.

Copy link

commented Jul 30, 2017

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented Sep 18, 2017

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

This comment has been minimized.

Copy link

commented Jan 2, 2018

How can i use this with angular4 ?
Please Help

@roydekleijn

This comment has been minimized.

Copy link

commented Mar 10, 2018

How to use with Angular 5 / typescript?

@nikuraj006

This comment has been minimized.

Copy link

commented Mar 12, 2018

image
i got this error how it solve

@Rajesh3646

This comment has been minimized.

Copy link

commented Mar 21, 2018

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

This comment has been minimized.

Copy link

commented Apr 12, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.