trim kaur
trim kaur

Reputation: 71

Uploading File using googledrive api in php

I have searched on how to upload files on googledriveapi using php.I used following method

$file-setMimetype='image/jpg';
$file->setTitle='abcd'
$service->files->insert($file).

It inserts file on googledrive with the title and mimetype but it is empty.My question is how to upload actual data or content contained in the file i.e. if I want to upload the image or pdf file from my system to googledrive.How do I.Please help me on how to send actual data in $data.What that $data variable should contain.

Upvotes: 1

Views: 6693

Answers (3)

Christoforos
Christoforos

Reputation: 723

There has been an update to the api and the documentation has not change accoringly. So on Claudio comment above the
"$file = new Google_DriveFile();"
should change to
$file = new Google_Service_Drive_DriveFile();

Upvotes: 0

KiL
KiL

Reputation: 1550

Try this:

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

You can take a look at this example of how to insert a file (Click to PHP tab). Try to upload a text/plain file with content first, image data may need to be encoded in base64 before you can add to content.

Upvotes: 0

Claudio Cherubino
Claudio Cherubino

Reputation: 15024

There's a 10-minute tutorial on how to write a complete PHP app to upload files to Drive in the recently added Quickstart page:

<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';

$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));

$service = new Google_DriveService($client);

$authUrl = $client->createAuthUrl();

//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));

// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);

//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');

$data = file_get_contents('document.txt');

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

print_r($createdFile);
?>

Upvotes: 2

Related Questions