Google Drive File Picker and Download the file

This articles should how to use picker on google drive and then download the picked files(limit to photos) use the javascript

Setup on google drive.

Go to the google developers console:  https://console.developers.google.com/
Create a new project or select a exist project,

and enable two libraries:  “Google Picker API” and “Google Drive API”
there are no special setup on “Google Picker API”, but for “Drive API”, it need go setup “Drive UI Integration”:

Client ID should same as the “OAuth 2.0 client IDs” in this project.
Open URL should same as the url of your web site domain, or a specific URL where you try to download the files.

Go back to Crediential of Oauth,

the same domain setup on previous steps is also list on “Authorized JavaScript origins”,

the open url we input on previous steps is list on “Authorized redirect URIs. it best list all your related URL into redirect URI.

prepare the keys we need on code step:

 //Google Client Id
var googleClientID='954222223338828-f21pukla0g67531760s0ed1575qaivth.apps.googleusercontent.com'
//Google App Id
var googleAppId='954222223338828'
//google drive picker
var googleDrivePickerDevelopKey='AIzaBHzK0WWvRj5DF9jgV6sTJpGwxzSyDfGcj0s'

That’s all in Google Console.

Let’s start write code for it.

First of all, insert the google js file into the html

<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
<script type="text/javascript" src="https://apis.google.com/js/client.js"></script>

The second js code is google client libriry,  it’s quickly and easy to use, but on this article, I’ll not use this one.

build the picker, remember we have 3 variables get from google console before, we need use on the code files.

First of all, let’s build the Picker.

/**Google drive ***/
var pickerApiLoaded = false;
var oauthToken;
var fileId;
//Photos Scope can't get the data we wanted, the solution, is use Drive only scope,
//And view.setMimeTypes("image/png,image/jpeg,image/jpg"); to only view the images
//  var googleScope = ['https://www.googleapis.com/auth/photos'];
var googleScope='https://www.googleapis.com/auth/drive.readonly'
// Use the Google API Loader script to load the google.picker script.

function loadPicker() {
    gapi.load('auth', {'callback': onAuthApiLoad});
    gapi.load('picker', {'callback': onPickerApiLoad});
}

function onAuthApiLoad() {
    window.gapi.auth.authorize(
        {
            'client_id': googleClientID,
            scope: googleScope,
            'immediate': false
        },
        handleAuthResult);
}

function onPickerApiLoad() {
    pickerApiLoaded = true;
    createPicker();
}

function handleAuthResult(authResult) {
    if (authResult &amp;&amp; !authResult.error) {
        oauthToken = authResult.access_token;
        createPicker();
    }
}

// Create and render a Picker object for searching images.
function createPicker() {
    if (pickerApiLoaded &amp;&amp; oauthToken) {
        var view = new google.picker.View(google.picker.ViewId.DOCS);
        view.setMimeTypes("image/png,image/jpeg,image/jpg");
        var picker= new google.picker.PickerBuilder()
            .enableFeature(google.picker.Feature.NAV_HIDDEN)
            .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
            .setAppId(googleAppId)
            .setDeveloperKey(googleDrivePickerDevelopKey)
            .setOAuthToken(oauthToken)
            .addView(view)
            .setCallback(pickerCallback)
            .build()
            .setVisible(true);

    }
}
// A simple callback implementation.
function pickerCallback(data) {
}<

We need download image after Picker, the photo scope on Picker can’t get the right file ID,  to solute this,  Use  drive scope and limit the mimeTypes.

Handle the data from File Picker and download it

function pickerCallback(data) {
 if (data.action == google.picker.Action.PICKED) {
 fileId = data.docs[0].id;
 $http.get('https://www.googleapis.com/drive/v2/files/' +fileId+ '?alt=media',
 {
   headers: {'Authorization': 'Bearer '+oauthToken}
 }).success(function(file){
   //file is the image object
 })
 }
}

$http is from angularJs, you can replace this with the js framework you used, or use the google client js library.

?alt=media

which will return the image, otherwise it will return json code with image name, image downloadUrl(that Url still need oauth token) etc.

headers: {'Authorization': 'Bearer '+oauthToken}

We need setup Authorization token on the hear, otherwise we can’t visit the file.

It’s simple, we can handle the image in the js code now,  but it’s not end for me, I need directly download the files on remote server, not download on the js code to user browser.

Let’s change the code to download the file on remote server

function pickerCallback(data) {
 if (data.action == google.picker.Action.PICKED) { 
   $http({
     method: 'POST',
     url: 'theUrlWhichDownloadImage.php',
     dataType: 'json',
     crossDomain: true,
     data: {
       oAuthToken:oauthToken,
       fileId: data.docs[0].id,
       name: data.docs[0].name,
       mimeType:data.docs[0].mimeType
     },
     headers: {'Content-Type': 'application/x-www-form-urlencoded'}
   })
   .success(function (data2) {

   })
   .error(function (data2) {

   });
 }
}

replace with get the files from google drive api, we send the file id, the oauth token to remote server, which used to download the file.

and on the remote server, a php file was created and recevied the data, try to download the file from google drive.

 

$request_body = file_get_contents('php://input');
$param = (array)json_decode($request_body);
$oAuthToken = $param['oAuthToken'];
$fileId = $param['fileId'];
$getUrl = 'https://www.googleapis.com/drive/v2/files/' . $fileId . '?alt=media'; //
$authHeader = 'Authorization: Bearer ' . $oAuthToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $getUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($authHeader));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);

The image was on $data. save it and return the path to js code on fronend.

$path='examplepath/';
file_put_contents($path.$param['name'], $data)
//return the file URL to js code.

Compare to OneDrive, DropBox,  Google Drive File Picker and download files is much more complex. hope this Article can help you.