Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Drive PHP API empty uploaded file

So I've been having weird issues with PHP upload with GAPI. The file actually gets created on the drive but for some reason the data doesn't make it to Google and it just creates a file with 0 bytes.

Here's 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 that's not the problem. When I output $data, I get the mess of crap that you usually get when pulling a file so I know that's not the issue.. All of the scopes should be right but here they are anyways:

$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");

No documentation I can find on this problem so any help would be really appreciated!

like image 600
ChrisB Avatar asked May 04 '14 02:05

ChrisB


1 Answers

I was able to figure this out and wanted to leave this for anyone else that might have this issue. Ended up looking through the source code and noticed an If statement that was not getting fired.

Change

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

To

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

It's just that easy! Hate it when it's that easy..

like image 62
ChrisB Avatar answered Sep 28 '22 02:09

ChrisB