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

前端 未结 2 1363
灰色年华
灰色年华 2020-12-03 18:25

I am having serious issues with the documentation for the new google drive API client library. It seems this should be an easy one to answer without having to put it on stac

相关标签:
2条回答
  • 2020-12-03 19:12

    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);
    
    0 讨论(0)
  • 2020-12-03 19:14

    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);
    }
    
    0 讨论(0)
提交回复
热议问题