我正在开始一些基于Google Drive的开发。"在Excel中编辑,放入数据库"之类的。问题是:我正试图从驱动器下载文件,但我无法获得downloadUrl属性。
我跟随这个页面,从谷歌自己:https://developers.google.com/drive/manage-downloads
它说我必须获得文件元数据,然后提取downloadUrl属性。
这和许可有关系吗?或者类似的事情?
编辑这是我正在使用的代码(部分)。首先,一个在Google页面
上显示的函数function downloadFile($service, $file) {
$downloadUrl = $file->getDownloadUrl();
if ($downloadUrl) {
$request = new Google_HttpRequest($downloadUrl, 'GET', null, null);
$httpRequest = Google_Client::$io->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200) {
return $httpRequest->getResponseBody();
}
}
}
其余代码仍为示例:
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('xxxxxxxxxxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:'n$authUrl'n'n";
print "Please enter the auth code:'n";
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
//Retrive a file
$file = new Google_DriveFile();
$file->setDownloadUrl("https://www.googleapis.com/drive/v2/files/{fileID}");
$requestedFile = json_decode(downloadFile($service, $file));
print_r($requestedFile);
打印时,我看不到downloadUrl属性。当然,我也不能访问它!
试试这个代码
$service = new Google_Service_Drive($client);
/** @var GuzzleHttp'Psr7'Response $content */
$content = $service->files->get($googleDriveId, ['alt' => 'media']);
我还建议您使用sdk v2,它集成了guzzle。这段代码将返回GuzzleHttp'Psr7'Response而不是string.
在我的博客中,我详细介绍了如何获得授权代码,然后获得目录列表。清单中的每个文件都有元数据,包括downloadUrl属性。这在博客中也有涉及。
我也试图下载一个文件,但我有一个不同的问题,但你可能会发现它在这里使用