【发布时间】:2012-12-10 20:17:47
【问题描述】:
我正在尝试通过他们的 PHP 客户端库使用 Google Drive API 来上传一个大文件。目前它失败了,因为似乎唯一可用的方法是“简单”上传方法。不幸的是,这需要您将整个文件作为数据加载,并且它达到了我的 php 内存限制。我想知道它是否可能,并看一个例子来说明它是如何完成的。我知道有一种可恢复和分块上传的方法,但没有关于如何使用它的文档。
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$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);
//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
?>
【问题讨论】:
-
大是一个相对术语。是10mb吗? 1GB? 10GB?
-
回答问题没关系。但是 10mb 的文件足够大,需要解决方案...... 5mb 通常会使“简单”上传失败。我一般需要上传 50mb 到 1gb 的文件。
-
在找到分段(可恢复)上传的代码之前,我遇到了同样的问题,如以下答案所示:stackoverflow.com/a/14693917/1060686。它应该允许您在通常的脚本内存限制内上传大文件(如果您有兴趣,可以使用相同的方法进行下载。另外,请确保您使用的是最新版本的 php 客户端 API [code.google.com/p/google-api-php-client/source/checkout]并且 $apiConfig['use_objects'] 在 config.php 上设置为 false) [1]: [2]:
标签: google-drive-api google-api-php-client