Empty uploaded Google API file for Google Drive

So, I am having strange problems loading PHP using GAPI. The file is actually created on disk, but for some reason the data does not go to Google, and it just creates a file with 0 bytes.

Here is my code:

function uploadFile($service, $title, $description, $parentId, $mimeType, $filepath) { $mimeType = "image/png"; $title = "test.png"; $file = new Google_Service_Drive_DriveFile(); $file->setTitle($title); $file->setDescription($description); $file->setMimeType($mimeType); // Set the parent folder. if ($parentId != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } try { $data = file_get_contents(); $createdFile = $service->files->insert($file, array( 'data' => $data, 'mimeType' => $mimeType, )); // Uncomment the following line to print the File ID // print 'File ID: %s' % $createdFile->getId(); //return $createdFile; } catch (Exception $e) { echo "An error occurred: " . $e->getMessage(); } } 

Everything is authenticated, so I know this is not a problem. When I output $ data, I get the mess of crap that you usually get when you pull out the file, so I know this is not a problem. All scopes should be correct, but here they are all the same:

 $client->addScope("https://www.googleapis.com/auth/drive"); $client->addScope("https://www.googleapis.com/auth/drive.file"); $client->addScope("https://www.googleapis.com/auth/drive.appdata"); $client->addScope("https://www.googleapis.com/auth/drive.scripts"); $client->addScope("https://www.googleapis.com/auth/drive.apps.readonly"); $client->addScope("https://www.googleapis.com/auth/drive.metadata.readonly"); $client->addScope("https://www.googleapis.com/auth/drive.readonly"); 

There is no documentation I can find on this issue, so any help would be really appreciated!

+6
source share
1 answer

I was able to figure this out and wanted to leave it to someone else who might have this problem. The source code scan ended and noticed an If statement that did not start.

Edit

 $createdFile = $service->files->insert($file, array( 'data' => $data, 'mimeType' => $mimeType, )); 

For

 $createdFile = $service->files->insert($file, array( 'data' => $data, 'mimeType' => $mimeType, 'uploadType' => 'media' //add this for pdfs to work )); 

It's just that simple! I hate it when it's easy ..

+6
source

All Articles