Google Drive PHP API - 简单文件上传

时间:2022-01-10 15:23:00

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:

我正在尝试编写一个小脚本,使用Google Drive PHP API将本地文件上传到Google云端硬盘。文档维护得很差,但到目前为止我很确定代码应该是这样的:

<?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!

我究竟做错了什么?您能否提供使用Google Drive PHP API将文件上传到Google云端硬盘的简单工作脚本?先谢谢你!

2 个解决方案

#1


18  

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


1  

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);
    ?>

#1


18  

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


1  

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);
    ?>