Google Drive API - PHP Client Library - setting uploadType to resumable upload

烂漫一生 提交于 2019-11-27 15:12:32

The following sample will work with the latest version of the Google APIs PHP Client (https://code.google.com/p/google-api-php-client/source/checkout)

if ($client->getAccessToken()) {
  $filePath = "path/to/foo.txt";
  $chunkSizeBytes = 1 * 1024 * 1024;

  $file = new Google_DriveFile();
  $file->setTitle('My document');
  $file->setDescription('A test document');
  $file->setMimeType('text/plain');

  $media = new Google_MediaFileUpload('text/plain', null, true, $chunkSizeBytes);
  $media->setFileSize(filesize($filePath));

  $result = $service->files->insert($file, array('mediaUpload' => $media));

  $status = false;
  $handle = fopen($filePath, "rb");
  while (!$status && !feof($handle)) {
    $chunk = fread($handle, $chunkSizeBytes);
    $uploadStatus = $media->nextChunk($result, $chunk);
  }

  fclose($handle);
}

This may be a newer reference, but here is Google's official take on this question: https://developers.google.com/api-client-library/php/guide/media_upload

From the article:

Resumable File Upload

It is also possible to split the upload across multiple requests. This is convenient for larger files, and allows resumption of the upload if there is a problem. Resumable uploads can be sent with separate metadata.

$file = new Google_Service_Drive_DriveFile();
$file->title = "Big File";
$chunkSizeBytes = 1 * 1024 * 1024;

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

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

// Upload the various chunks. $status will be false until the process is
// complete.
$status = false;
$handle = fopen("path/to/file", "rb");
while (!$status && !feof($handle)) {
  $chunk = fread($handle, $chunkSizeBytes);
  $status = $media->nextChunk($chunk);
 }

// The final value of $status will be the data from the API for the object
// that has been uploaded.
$result = false;
if($status != false) {
  $result = $status;
}

fclose($handle);
// Reset to the client to execute requests immediately in the future.
$client->setDefer(false);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!