使用gdrive php客户端上传大文件时出现问题

时间:2018-01-23 04:04:00

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

我收到以下错误:

PHP致命错误:未捕获的异常“Google_Service_Exception”,消息“无法解析内容范围标头”。在vendor / google / apiclient / src / Google / Http / REST.php:118

堆栈追踪:

  

0 vendor / google / apiclient / src / Google / Http / REST.php(94):Google_Http_REST :: decodeHttpResponse(Object(GuzzleHttp \ Psr7 \ Response),Object(GuzzleHttp \ Psr7 \ Request),NULL)

     

1 [内部函数]:Google_Http_REST :: doExecute(Object(GuzzleHttp \ Client),Object(GuzzleHttp \ Psr7 \ Request),NULL)

     

2 vendor / google / apiclient / src / Google / Task / Runner.php(176):call_user_func_array(Array,Array)

     

3 vendor / google / apiclient / src / Google / Http / REST.php(58):Google_Task_Runner-run()

     

4 vendor / google / apiclient / src / Google / Client.php(788):/ var / www / html / website-redesign / application / libraries / hla_app_log / vendor / google / apiclient / src / Google /中的Google_Http_R第118行的Http / REST.php

上传代码:

function uploadInBatch($client,$service, $parentId,$backup_file) {

$file = new Google_Service_Drive_DriveFile();
$file->title = 'backup.sql';
$file->setParents(array($parentId));
$filesize = filesize($backup_file);

$chunkSizeBytes = $filesize/20;

// Call the API with the media upload, defer so it doesn't immediately return.
$client->setDefer(true);
$request = $service->files->create($file);

// Create a media file upload to represent our upload process.
$media = new Google_Http_MediaFileUpload(
  $client,
  $request,
  'application/sql',
  null,
  true,
  $chunkSizeBytes
);
$media->setFileSize($filesize);

$status = false;
$handle = fopen($backup_file, "rb");

$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
$resumeUri = $media->getResumeUri();
$offset = ftell($handle);

while (!$status) {

    if($resumeUri){
        $result = $media->resume($resumeUri);
    }

    fseek($handle, $offset);   
    $chunk = fread($handle, $chunkSizeBytes);
    $status = $media->nextChunk($chunk);
    if(!$status){ //nextChunk() returns 'false' whenever the upload is still in progress
        echo 'sucessfully uploaded ' . ($media->getProgress()/$filesize)*100 . ' %';
    }

}
fclose($handle);
// Reset to the client to execute requests immediately in the future.
$client->setDefer(false);
}

以上功能用于上传大约2GB的文件

1 个答案:

答案 0 :(得分:0)

我之前已经看过这个问题,因为API不允许你上传真正大的文件。

您可以考虑按照找到的here示例,它看起来与您的代码略有不同。

// Create a MediaFileUpload object for resumable uploads.
    $media = new Google_Http_MediaFileUpload(
        $client,
        $insertRequest,
        'video/*',
        null,
        true,
        $chunkSizeBytes
    );
    $media->setFileSize(filesize($videoPath));


    // Read the media file and upload it chunk by chunk.
    $status = false;
    $handle = fopen($videoPath, "rb");
    while (!$status && !feof($handle)) {
      $chunk = fread($handle, $chunkSizeBytes);
      $status = $media->nextChunk($chunk);
    }