【问题标题】:Google Drive PHP API - File UploadGoogle Drive PHP API - 文件上传
【发布时间】:2020-03-20 01:30:02
【问题描述】:

我正在尝试使用 php 中的 google drive api 在 google drive 中上传文件。 我正确地从谷歌驱动器获取文件名和 ID。但它无法将文件上传到谷歌驱动器并显示一些错误。我无法确定是否缺少某些客户端库包或其中发生了其他事情

Fatal error: Uncaught Google_Service_Exception: { "error": { "errors": [ { "domain": "global", "reason": "insufficientPermissions", "message": "Insufficient Permission: Request had insufficient authentication scopes." } ], "code": 403, "message": "Insufficient Permission: Request had insufficient authentication scopes." } } in C:\xampp\htdocs\googledrive\vendor\google\apiclient\src\Google\Http\REST.php:118 Stack trace: #0 C:\xampp\htdocs\googledrive\vendor\google\apiclient\src\Google\Http\REST.php(94): Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #1 C:\xampp\htdocs\googledrive\vendor\google\apiclient\src\Google\Task\Runner.php(181): Google_Http_REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #2 C:\xampp\htdocs\googledrive\vendor\google\apiclient\src\Google\Http\REST.php(58): Google_Task_Runner->run() #3 C:\xampp\htdocs\googledrive\vendor\google\apiclient\src\Google in C:\xampp\htdocs\googledrive\vendor\google\apiclient\src\Google\Http\REST.php on line 118

我的源代码是

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



/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Drive API PHP Quickstart');
    $client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
    $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.
$optParams = array(
  'pageSize' => 10,
  '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</br>", $file->getName(), $file->getId());
    }
}



$pasta      = 'img';   
$arquivo    = 'photo.jpg'; // file.mp4
    printf("Folder: %s || File: %s\n", $pasta, $arquivo);


$parentId   = 'replace with Folder ID';


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.' =====WITHOUT FILES========'.PHP_EOL;

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

}


请帮帮我,这背后的问题是什么。

【问题讨论】:

    标签: php api upload drive


    【解决方案1】:

    DRIVE_METADATA_READONLY 的范围是https://www.googleapis.com/auth/drive.metadata.readonly。在这种情况下,不能使用 Files:create 的方法。我认为您的错误消息的原因是这个。那么在这种情况下,如何修改如下?

    我认为你脚本的其他部分也可以。

    发件人:

    $client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
    

    收件人:

    $client->setScopes(Google_Service_Drive::DRIVE);
    
    • DRIVE的范围是https://www.googleapis.com/auth/drive

    注意:

    • 修改范围时,请删除$tokenPath = 'token.json';token.json文件,重新授权范围。这样,新的作用域就会反映到访问令牌和刷新令牌中。请注意这一点。

    参考资料:

    如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

    【讨论】:

      【解决方案2】:
      • 驱动器。谷歌 .com
      • 按“新建”
      • 复制并粘贴您的源代码并保存

      【讨论】:

      • OP 显然想要使用 API,而不是按“新”等。(这也不是如何拼写“粘贴”。)
      猜你喜欢
      • 1970-01-01
      • 2023-03-30
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多