簡體   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