Google Drive PHP API-文件上传

问题描述 投票:0回答:2

[我正在尝试使用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
2个回答
0
投票

这个答案怎么样?

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

注意:

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

参考:

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


0
投票
  • 驱动器。 google .com
  • 按“新”
  • 复制并粘贴您的源代码并保存
© www.soinside.com 2019 - 2024. All rights reserved.