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

How to update file in google drive v3 PHP


I cant seem to update file in google drive with the following code, everything goes fine but file remains untouched? I am working with v3 api.

 function updateFile($service, $fileId, $data) {
        try {
            $emptyFile = new Google_Service_Drive_DriveFile();
            $file = $service->files->get($fileId);
            $service->files->update($fileId, $emptyFile, array(
                'data' => $data,
                'mimeType' => 'text/csv',
                'uploadType' => 'multipart'
            ));
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }

Solution

  • I managed to do it, you have to put empty file as second argument, not sure why but this post helped me a lot: Google Drive API v3 Migration

    This is final solution:

    function updateFile($service, $fileId, $data) {
            try {
                $emptyFile = new Google_Service_Drive_DriveFile();
                $service->files->update($fileId, $emptyFile, array(
                    'data' => $data,
                    'mimeType' => 'text/csv',
                    'uploadType' => 'multipart'
                ));
            } catch (Exception $e) {
                print "An error occurred: " . $e->getMessage();
            }
        }
    

    where $fileId is file you are updating, and data is new content you are updating your file.

    Dont forget to refresh google drive after this because it's preview doesnt change and I lost one hour on that :/. Hope this helps.