Google Drive V3,Google API客户端2.0 - 批量上传失败

时间:2016-02-21 04:40:43

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

使用带有API主分支(v2.0)的Google Drive V3批量上传失败。

我已使用服务帐户凭据修改了https://github.com/google/google-api-php-client/blob/master/examples/batch.php

代码:

include_once __DIR__ . '/../vendor/autoload.php';
include_once "templates/base.php";

echo pageHeader("Batching Queries");

// USE TRUE OR FALSE TO TOGGLE BETWEEN BATCHED AND SEQUENTIAL UPLOADS.
$useBatch = true;

$client = new Google_Client();
$client->setScopes([
    'https://www.googleapis.com/auth/drive',
]);
if ($credentials_file = checkServiceAccountCredentialsFile()) {
  // set the location manually
  $client->setAuthConfig($credentials_file);
} elseif (getenv('GOOGLE_APPLICATION_CREDENTIALS')) {
  // use the application default credentials
  $client->useApplicationDefaultCredentials();
} else {
  exit;
}
$client->setSubject('some@email.com');
$service = new Google_Service_Drive($client);
$client->setUseBatch($useBatch);

if ($useBatch) {
    $batch = $service->createBatch();
}

$folder = new Google_Service_Drive_DriveFile([
  'name' => 'Invoices',
  'mimeType' => 'application/vnd.google-apps.folder'
]);

$req = $service->files->create($folder, [
  'fields' => 'id'
]);

if ($useBatch) {
    $result = $batch->add($req, 'newfolder');
    $folder = $batch->execute()['response-newfolder'];
    $newFolderId = $folder->id;
} else {
    $newFolderId = $req->id;
}

$uploadIDs = null;

if ($useBatch) {
    $batch = $service->createBatch();
}

for ($i=1;$i<=3;$i++) {
    $file = new Google_Service_Drive_DriveFile([
        'name' => $i . '.jpg',
        'mimeType' => 'image/jpeg',
        'parents' => [$newFolderId],
    ]);

    $req = $service->files->create($file, [
        'data' => file_get_contents('img/'.$i.'.jpg'),
        'mimeType' => 'image/jpeg',
        'uploadType' => 'media',
        'fields' => 'id',
    ]);

    if ($useBatch) {
        $batch->add($req, $i);
    } else {
        $uploadIDs[] = $req->id;
    }
}

if ($useBatch) {
    $results = $batch->execute();
} else {
    print_r($uploadIDs);
}

运行最后$ results = $ batch-&gt; execute()后,上面的代码将失败并显示“Not Found” (文件夹发票将成功创建)。

使用$useBatch = false一切都按预期工作 - 创建一个文件夹,其中包含三个文件。

为什么批量上传会崩溃?

谢谢!

2 个答案:

答案 0 :(得分:0)

  

当前,Google云端硬盘不支持媒体批量处理,   用于上传或下载

来源:https://developers.google.com/drive/api/v3/batch

答案 1 :(得分:-1)

根据Official Google Documentation,由于用户没有对文件的读取权限或文件不存在,您收到了“ 404找不到文件”。建议的操作:向用户报告他们对文件没有读取权限或文件不存在。告诉他们他们应该要求所有者获得该文件的许可。

您必须在request中加入“ $ fileId ”。此外,如果' $ useBatch = true ',您应该设置' $ userPermission '。

注意:您应该使用v1-branch

中所述的https://github.com/google/google-api-php-client