Google picker and backend file download

雨燕双飞 提交于 2019-12-01 04:05:30

Finally, I found a solution.

If you want to download a file, you need two variables - oAuthToken and fileId

oAuthToken you get from JS client side when user authenticates. If you use the example from google docs (https://developers.google.com/picker/docs/), the function looks like this:

function handleAuthResult(authResult) {
    if (authResult && !authResult.error) {
        oauthToken = authResult.access_token;
        oauthToken; // <-- THIS IS THE Bearer token
        createPicker();
        }
}

fileId you get from when user picks a file. Again, a modified example from google docs:

function pickerCallback(data) {
    if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
        var doc = data[google.picker.Response.DOCUMENTS][0];
        alert('You picked fileId: ' + doc[google.picker.Document.ID]);
    }
}

Probably you will pass these data as a form request, or through ajax. Simple cURL call from backend to download the file:

$oAuthToken = 'ya29.XXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXX-XXXXXXX-XXXXXX-X-XXXXXXXXXXXX-XXXX';
$fileId = '0B4zzcXXXXXXXXXXXXXXXXXXXXXX';

$getUrl = 'https://www.googleapis.com/drive/v2/files/' . $fileId . '?alt=media';
$authHeader = 'Authorization: Bearer ' . $oAuthToken ;


$ch = curl_init($url);

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

curl_setopt($ch, CURLOPT_HTTPHEADER, [$authHeader]);

$data = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_errno($ch);


$data = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);

file_put_contents("destination-file.jpg", $data);

Docs about file download: https://developers.google.com/drive/web/manage-downloads Actually, everything was given to us, but we couldn't move our brains a little to make out the actual code :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!