JanLi
JanLi

Reputation: 71

Google picker selected file callback

i have integrated and try to use the google picker api google picker api but can i turn the callback into file ? so i can upload the file to my server

function pickerCallback(data) { 
  if (data.action == google.picker.Action.PICKED) {
    var fileId = data.docs[0].id; alert('The user selected: ' + fileId); 
  } 
} 

Upvotes: 1

Views: 647

Answers (1)

ziganotschka
ziganotschka

Reputation: 26796

Once you have the fileId, you can download the file as explained in the documentation for Download files with the Drive API

Unfortunately, there is no sample for Browser Javascript, but you use e.g. XML HttpRequests.

Sample:

//provided you already have the following line from previous steps:
oauthToken = authResult.access_token;

var doc = data[google.picker.Response.DOCUMENTS][0];
var mimeType = doc[google.picker.Document.MIME_TYPE];

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.googleapis.com/drive/v3/files/"+fileId+'?alt=media', true);
xhr.setRequestHeader('Authorization','Bearer '+oauthToken);
xhr.responseType = 'arraybuffer'
xhr.onload = function(){
    var base64 = 'data:' + mimeType + ';base64,' + base64ArrayBuffer(xhr.response);
//now you have the file content as binary data (ArrayBuffer) - proceed as desired
}
xhr.send();

Note:

you can modify xhr.responseType to e.g. blob or another responseType depending on your situation.

Alternatively you could also perform a Fetch request to 'https://www.googleapis.com/drive/v3/files' to obtain the file blob.

Upvotes: 1

Related Questions