Search code examples
phpgoogle-drive-apigoogle-drive-shared-drive

How to upload files to Google drive Shared drive folder?


Actually this code is uploading files to normal Gdrive but i need to upload my files into the shared drive can anyone help me. All i need is to Upload my files to to my shared drive. Below is my current code :-

require __DIR__ . '/vendor/autoload.php';

use Google\Client;
use Google\Service\Drive;
# TODO - PHP client currently chokes on fetching start page token
function uploadBasic()
{
    try {
        $client = new Client();
        putenv('GOOGLE_APPLICATION_CREDENTIALS=./credentials.json');
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);

        $file = getcwd().'/637fdc0994855.mp4';
        $filename = basename($file);
        $mimeType = mime_content_type($file);

        $fileMetadata = new Drive\DriveFile(array(
            'name' => $filename,
            'parents' => ['1VBi8C04HBonM6L4CfL-jHWZ0QoQRyrCL']
        ));
        $content = file_get_contents('637fdc0994855.mp4');
        $file = $driveService->files->create($fileMetadata, array(
            'data' => $content,
            'mimeType' => $mimeType,
            'uploadType' => 'multipart',
            'fields' => 'id'
        ));
        printf("File ID: %s\n", $file->id);
        return $file->id;
    } catch (Exception $e) {
        echo "Error Message: " . $e;
    }
}
uploadBasic();

Solution

  • In order to upload the file to the shared drive, please modify as follows.

    From:

    $file = $driveService->files->create($fileMetadata, array(
        'data' => $content,
        'mimeType' => $mimeType,
        'uploadType' => 'multipart',
        'fields' => 'id'
    ));
    

    To:

    $file = $driveService->files->create($fileMetadata, array(
        'data' => $content,
        'mimeType' => $mimeType,
        'uploadType' => 'multipart',
        'fields' => 'id',
        'supportsAllDrives' => true // <--- Added
    ));
    

    Note:

    • In this case, your client has no permission for writing the shared drive, an error occurs. Please be careful about this.

    Reference: