Monday, August 31, 2015

Upload a file to Google Drive via PHP using REST

Disclaimer: I am (at best) a novice PHP coder.  There may well be better ways to accomplish this task, but this is what worked for me.

First off, Google does provide a nice-looking PHP library for working with Drive, but I was reluctant to introduce more libraries into our already complex and fragile server environment.

Using REST, Google's  documentation explains that there are three ways to upload files to Drive - using a media upload, a multipart upload, and a resumable upload. 

For our task, we were working with small spreadsheets so the resumable upload was overkill.

We really wanted to use multipart but gave up after many hours of trying but getting only 400 - Bad Request errors.  We tried using the exact type message that Google detailed in its documentation, but it still didn't work.   (Had I been a better PHP programmer, perhaps I could have figured out what was wrong).

Anyways, we moved on and used a combination of a media POST, to upload the file contents followed by a PATCH, to update the title.  Here's the code:


POSTing the file to upload.  (Assumes you have an authorization token).  The result of the file_get_contents call will be a JSON structure that represents a file resource.


$authstr = 'Bearer '.$token;

$fileToUpload = "datafiles/".$_FILES['uploadedFile']['name'].".csv";

$url = 'https://www.googleapis.com/upload/drive/v2/files?uploadType=media&convert=true'; 

$options = array(
        'http' => array(
            'header'  => "Content-type: application/vnd.ms-excel\r\nAuthorization: ".$authstr."\r\n",
            'method'  => 'POST',
            'content' => file_get_contents($fileToUpload),
        ),
 );
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

$json = json_decode($result);


PATCHing the file to change the title.  We use a different URL here and identify the file using the File Id returned from the media upload POST.  We tell it that we're passing a JSON structure and send along the attributes to change.


$url = 'https://www.googleapis.com/drive/v2/files/'.$json->id;
 

$options = array(
        'http' => array(
            'header'  => "Content-type: application/json\r\nAuthorization: ".$authstr."\r\n",
            'method'  => 'PATCH',
            'content' => '{"title" : "My New Filename"}',
        ),
 );

$context  = stream_context_create($options);

$result = file_get_contents($url, false, $context);
$json = json_decode($result);



Have a better solution?  I'd be interested to hear about it....




No comments:

Post a Comment