8

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();
        }
    }
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
MapleSyrup
  • 313
  • 2
  • 9
  • Can you provide the full request and response for this? Have you tried with other different file types (i.e. google docs)? Does that work accordingly? – Andres Feb 10 '16 at 00:27

2 Answers2

21

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.

Community
  • 1
  • 1
MapleSyrup
  • 313
  • 2
  • 9
0
 function updateFile($fileId,$newDescription){
        try {    
            // First retrieve the file from the API. 
            $emptyFile = new Google_Service_Drive_DriveFile();
            // File's new metadata.   
            $emptyFile->setDescription($newDescription);
            // Send the request to the API.
            $driveService->files->update($fileId, $emptyFile, array());
            print 'success';
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }//end update

The method is essential if you wish to update staff like desciption. I copied the idea from v2.

// File's new metadata.
$file->setTitle($newTitle);
$file->setDescription($newDescription);
$file->setMimeType($newMimeType);

NB: Also you have to ensure 3 parameter of update function is an array Also as stated in other helpful answer; Ensure you refresh google drive to check

James Ikubi
  • 2,552
  • 25
  • 18