Search code examples
phpgoogle-apigoogle-drive-apigoogle-api-php-client

Problem with upload image to google drive using php


On my site I use google api to upload images in folder. Actually, there is no official documentation from google how to use api using php, only python, js and etc. Current problem is that I get no errors, but file isn't uploading. I'm 100% sure that my service workers work (sorry for such bad english) properly. Below I put my php code for uploading images:

<?php
include '../vendor/autoload.php';

function handleGoogleDrive($file)
{
    //connecting to google drive
    $client = new \Google_Client();
    $client->setApplicationName('Somesite');
    $client->setScopes([\Google_Service_Drive::DRIVE]);
    $client->setAccessType('offline');
    $client->setAuthConfig('./credentials.json');
    $client->setClientId('2445617429-6k99ikago0s0jdh5q5k3o37de6lqtsd3.apps.googleusercontent.com');
    $client->setClientSecret('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');
    $service = new Google_Service_Drive($client);
    //counting amount of files in folder, there is no real reason in doing that
    //it is just a test of connecting
    $folder_id = '1eQtNOJjlA2CalZYb90bEs34IaP6v9ZHM';
    $options = [
        'q' => "'" . $folder_id . "' in parents",
        'fields' => 'files(id, name)'
    ];
    //printing result
    $results = $service->files->listFiles($options);
    echo count($results->getFiles());
    //trying to add file
    $data = file_get_contents("../test.jpg");
    $file = new Google_Service_Drive_DriveFile();
    $file->setName(uniqid(). '.jpg');
    $file->setDescription('A test document');
    $file->setMimeType('image/jpeg');
    $new_file = $service->files->create($file, [
        'data' => $data,
        'mimeType' => 'image/jpeg',
        'uploadType' => 'multipart',
    ]);
    print_r($new_file);
}

Solution

  • This is my standard upload code for uploading.

    Try removing 'uploadType' => 'multipart', in your code.

    I also cant see you setting the folder id when you upload your file which means its going to root directory.

    // Upload a file to the users Google Drive account
    try{
        $filePath = "image.png";
        $folder_id = '1eQtNOJjlA2CalZYb90bEs34IaP6v9ZHM';
        $fileMetadata = new Drive\DriveFile();
        $fileMetadata->setName("image.png");
        $fileMetadata->setMimeType('image/png');
        $fileMetadata->setParents(array($folder_id));
    
        $content = file_get_contents($filePath);
        $mimeType=mime_content_type($filePath);
    
        $request  = $service->files->create($fileMetadata, array(
            'data' => $content,
            'mimeType' => $mimeType,
            'fields' => 'id'));
    
        printf("File ID: %s\n", $request->id);
    }
    catch(Exception $e) {
        // TODO(developer) - handle error appropriately
        echo 'Message: ' .$e->getMessage();
    }
    

    Remember if you are using a service account, files are uploaded to the service accounts drive account unless you add the folder you want to upload the file to.

    files list

    // Print the next 10 events on the user's drive account.
    try{
    
    
        $optParams = array(
            'pageSize' => 10,
            'fields' => 'files(id,name,mimeType)'
        );
        $results = $service->files->listFiles($optParams);
        $files = $results->getFiles();
    
        if (empty($files)) {
            print "No files found.\n";
        } else {
            print "Files:\n";
            foreach ($files as $file) {
                $id = $file->id;
    
                printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
            }
        }
    }
    catch(Exception $e) {
        // TODO(developer) - handle error appropriately
        echo 'Message: ' .$e->getMessage();
    }