Google Drive PHP API - Simple File Upload

末鹿安然 提交于 2019-11-26 08:09:20

问题


I am trying to write a small script to upload a local file to Google Drive, using Google Drive PHP API. The documentation is very poor maintained, but so far I am pretty sure the code should be looking like that:

<?php

include_once \'Google/Client.php\';
include_once \'Google/Service/Drive.php\';
include_once \'Google/Auth/OAuth2.php\';

$client = new Google_Client();

$client->setScopes(array(\'https://www.googleapis.com/auth/drive.file\'));
$client->setClientId(\'dfgdfgdg\');
$client->setClientSecret(\'dfgdfgdf\');
$client->setRedirectUri(\'urn:ietf:wg:oauth:2.0:oob\');


$service = new Google_Service_Drive($client);

$data = file_get_contents(\"a.jpg\");

// create and upload a new Google Drive file, including the data
try
{
//Insert a file
$file = new Google_Service_Drive_DriveFile($client);

$file->setTitle(uniqid().\'.jpg\');
$file->setMimeType(\'image/jpeg\');

$createdFile = $service->files->insert($file, array(
    \'data\' => $data,
    \'mimeType\' => \'image/jpeg\',
    \'uploadType\' => \'media\',
));
}
catch (Exception $e)
{
    print $e->getMessage();
}

print_r($createdFile);

?>

The issue is I am not able to do the authentication right (or I am doing something else wrong?). The error I received is:

HTTP Error: Unable to connect: \'fopen(compress.zlib://https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart) [function.fopen]: failed to open stream: operation failed\'

Followed by this error:

Notice: Undefined variable: createdFile in C:\\wamp\\www\\GoogleAPI\\index.php on line 39

What am I doing wrong? Can you provide a simple working script of uploading a file to Google Drive using Google Drive PHP API? Thank you in advance!


回答1:


Use this code to authenticate and upload a test file. You need to set <YOUR_REGISTERED_REDIRECT_URI> (and also in console) to this document itself to authenticate.

require_once 'Google/Client.php';
require_once 'Google/Service/Drive.php';

$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('<YOUR_CLIENT_ID>');
$client->setClientSecret('<YOUR_CLIENT_SECRET>');
$client->setRedirectUri('<YOUR_REGISTERED_REDIRECT_URI>');
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));

session_start();

if (isset($_GET['code']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'])) {
    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        $_SESSION['access_token'] = $client->getAccessToken();
    } else
        $client->setAccessToken($_SESSION['access_token']);

    $service = new Google_Service_Drive($client);

    //Insert a file
    $file = new Google_Service_Drive_DriveFile();
    $file->setName(uniqid().'.jpg');
    $file->setDescription('A test document');
    $file->setMimeType('image/jpeg');

    $data = file_get_contents('a.jpg');

    $createdFile = $service->files->create($file, array(
          'data' => $data,
          'mimeType' => 'image/jpeg',
          'uploadType' => 'multipart'
        ));

    print_r($createdFile);

} else {
    $authUrl = $client->createAuthUrl();
    header('Location: ' . $authUrl);
    exit();
}



回答2:


Use this

<?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 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();
    $localfile = 'a.jpg';
    $title = basename($localfile);
    $file->setTitle($title);
    $file->setDescription('My File');
    $file->setMimeType('image/jpeg');

    $data = file_get_contents($localfile);

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

    print_r($createdFile);
    ?>


来源:https://stackoverflow.com/questions/25707891/google-drive-php-api-simple-file-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!