Google Drive API v3 - 使用PHP下载文件

jeo*_*tl3 6 google-drive-api google-api-php-client

我正在尝试使用PHP了解Google Drive API v3的下载流程.使用API​​ v2下载文件I:

  • 获得了文件元数据
  • 使用downloadUrl参数获取文件的直接链接,将oAuth令牌附加到该文件并向其发出GET请求.

使用API​​ v3这似乎已被弃用,并且根据您在Drive Service上调用的文档files->get(),其数组参数"alt" => "media"为获取文件本身而不是元​​数据.

他们的例子是:

$fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M';
$content = $driveService->files->get($fileId, array(
'alt' => 'media' ));
Run Code Online (Sandbox Code Playgroud)

我无法理解它是如何工作的,并且已经通过代码进行了搜索,但它没有提供更多信息.

当你打电话时get(),$content实例中会涉及到什么?它是文件的内容(在这种情况下,这在处理大文件时似乎很麻烦 - 当然你会忘记内存?!)或者是否可以调用某种类型的流引用fopen?如何将此文件保存到磁盘?

文档并没有真正详细说明在进行API调用时会发生什么,它只是说它执行文件下载?

jeo*_*tl3 13

经过一些实验,我想通了.

当您get()使用alt=>media文档中指定的参数调用方法时,您将获得基础HTTP响应,这是一个Guzzle响应对象(显然客户端库使用Guzzle进行底层传输).

从那里你可以调用任何Guzzle响应方法,$response->getStatusCode()或者你可以获得实际文件内容的流.

如果他们在某处记录了这些内容会有所帮助!

编辑:这是一个粗略的例子,如果其他人不知道如何保存文件.

<?php

date_default_timezone_set("Europe/London");
require_once 'vendor/autoload.php';

// I'm using a service account, use whatever Google auth flow for your type of account.

putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account/key.json');
$client = new Google_Client();
$client->addScope(Google_Service_Drive::DRIVE);
$client->useApplicationDefaultCredentials();

$service = new Google_Service_Drive($client);

$fileId = "0Bxxxxxxxxxxxxxxxxxxxx"; // Google File ID
$content = $service->files->get($fileId, array("alt" => "media"));

// Open file handle for output.

$outHandle = fopen("/path/to/destination", "w+");

// Until we have reached the EOF, read 1024 bytes at a time and write to the output file handle.

while (!$content->getBody()->eof()) {
        fwrite($outHandle, $content->getBody()->read(1024));
}

// Close output file handle.

fclose($outHandle);
echo "Done.\n"

?>
Run Code Online (Sandbox Code Playgroud)