For large files, use resumable uploads to split the data into chunks across multiple requests. This allows for resuming the upload if a connection error occurs.
To implement this:
- Set the client to deferred mode using
$client->setDefer(true). - Initialize a
Google\Http\MediaFileUpload object with the client, the request, the MIME type, and a chunk size. - Iterate through the file in chunks using
$media->nextChunk($chunk) until the upload is complete. - Reset the client to non-deferred mode using
$client->setDefer(false) once finished.
$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);