带有PHP客户端2.0的Google Drive API V3 - 在单个请求中下载文件内容和元数据

时间:2016-02-25 00:44:01

标签: google-api google-drive-api google-api-php-client

我正在尝试使用带有Drive API V3的PHP客户端v2.0从Google云端硬盘下载文件。

是否可以在单个HTTP请求中检索文件的正文和元数据?

'alt=media'提供给->files->get()会返回GuzzleHttp\Psr7\Response我可以->getBody()->__toString()运行。

如果我不提供'alt=media',则会返回包含所有元数据但没有正文的Google_Service_Drive_DriveFile

问题。

是否可以在同一个请求中获取元数据和正文?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

<?php

//首先看一下:https://developers.google.com/api-client-library/php/auth/web-app

require_once __DIR__ . '/vendor/autoload.php';

//更改为您的时区     date_default_timezone_set( '太平洋/奥克兰');

$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setIncludeGrantedScopes(true);

//将范围更改为您需要的范围

$client->addScope(Google_Service_Drive::DRIVE_FILE, Google_Service_Drive::DRIVE_APPDATA, Google_Service_Drive::DRIVE, Google_Service_Drive::DRIVE_METADATA);
$accessToken = json_decode(file_get_contents('credentials.json'), true);
$client->setAccessToken($accessToken);

//如果令牌已过期,请刷新令牌。 Google会在一小时后将其过期

if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents('credentials.json', json_encode($client->getAccessToken()));
}

$service = new Google_Service_Drive($client);
$results = $service->files->listFiles($optParams);
$fileId = 'yourfileid;
$file = $service->files->get($fileId, array('alt' => 'media'));
file_put_contents("hello.pdf",$file->getBody());
?>