繁体   English   中英

Google Drive PHP API - 简单的文件上传

[英]Google Drive PHP API - Simple File Upload

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

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

?>

问题是我无法正确进行身份验证(或者我做错了什么?)。 我收到的错误是:

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'

随后出现此错误:

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

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

使用此代码验证和上传测试文件。 您需要将<YOUR_REGISTERED_REDIRECT_URI> (以及在控制台中)设置为该文档本身以进行身份​​验证。

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();
}

用这个

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

我能够运行在 CRON 中添加的 PHP。 他只在第一次要求验证码,然后一切正常。 我已经运行 CRON 超过 16 小时了,一切正常。

好吧,考虑到您已经完成了以下步骤:

  1. 在 Google Cloud Platform 上创建项目;
  2. 在 Credentials 中,您已经拥有 OAuth 2.0 客户端 ID;
  3. 下载凭据并重命名为credentials.json;
  4. 使用 composer 下载 Google Drive 库;

参考资料:

这里的代码是上传到特定子文件夹中的 Google Drive 的“工作”结果。 我希望它有帮助。

<?php

ini_set('memory_limit', '4096M');

require __DIR__ . '/vendor/autoload.php';

function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Drive API PHP Quickstart');
    $client->setScopes(Google_Service_Drive::DRIVE);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');


    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

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

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}


// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);

// Print the names and IDs for up to 10 files.
// Esse resultado é importante para ver que tudo está concetado;
// Esse comando deve exibir as ultimas 3 atividades do seu drive;
$optParams = array(
  'pageSize' => 3,
  'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);

if (count($results->getFiles()) == 0) {
    print "No files found.\n";
} else {
    print "Files:\n";
    foreach ($results->getFiles() as $file) {
        printf("%s (%s)\n", $file->getName(), $file->getId());
    }
}
//
// Fim atividades do Drive;
//


//Define variáveis de arquivos
//Aqui você pode substituir depois par algum array ou resultado do banco de dados
//Defina um bem simples inicialmente para ver que tudo funciona
$pasta      = 'substitua pela pasta';   // Um exemplo aqui é /home/usuario/public_html/arquivos_upload
$arquivo    = 'substitua pelo arquivo'; // arquivo.mp4
    printf("Pasta: %s || Arquivo: %s\n", $pasta, $arquivo);
}

//Essa é a pasta destino do Google Drive
$parentId   = 'substitua pelo ID da Pasta';


if ( !empty($arquivo) ) {

    //Define localização da pasta e arquivo
    $file_path = $pasta.'/'.$arquivo;

    //Conecta no Drive da sua conta
    $file = new Google_Service_Drive_DriveFile();

    //Define nome do arquivo
    $file->setName($arquivo);

    //Define Diretório Destino lá no Google Drive
    $file->setParents(array($parentId));

    //Cria o arquivo no GDrive
    $service->files->create(
      $file,
      array(
        'data'          => file_get_contents($file_path),
        'mimeType'      => 'application/octet-stream',
        'uploadType' => 'resumable'
      )
    );

    // Grava Log do que foi feito UTC -3 horas;
    $DateTime = new DateTime();
    $DateTime->modify('-3 hours');
    $now = $DateTime->format("Y-m-d H:i:s");
    $logfile = $now.' Upload OK :: '.$arquivo.PHP_EOL;

    $myfile = file_put_contents('logs.txt', $logfile, FILE_APPEND | LOCK_EX);

} else {

    //Grava Log
    $now = date("Y-m-d H:i:s");
    $logfile .=$now.' =====SEM ARQUIVOS========'.PHP_EOL;

    $myfile = file_put_contents('logs.txt', $logfile, FILE_APPEND | LOCK_EX);

}

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM