繁体   English   中英

无法通过Google API(PHP)将文件上传到Google云端硬盘

[英]Can't upload file to Google Drive via Google API (PHP)

当我尝试通过Google API( https://github.com/google/google-api-php-client )将文件上传到Google云端硬盘时,出现错误“权限不足”(读取文件没有任何问题)。 这是代码示例:

require_once 'google-api-php-client/vendor/autoload.php';

class GoogleConnector {
    private $client;
    public $report;

    function __construct($filesToSend, $backupFolder) {
        session_start();
        $this->client = new Google_Client();
        $this->client->setAuthConfig('client_secret.json');
        $this->client->addScope("https://www.googleapis.com/auth/drive");
        //also try different variants of this:
        //$this->client->setScopes(implode(' ', array(Google_Service_Drive::DRIVE)));

        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
            $this->client->setAccessToken($_SESSION['access_token']);
            $service = new Google_Service_Drive($this->client);
            $folderId = "FolderIdFromGoogleDrive";

            $this->report = "";
            foreach ($filesToSend as $file) {
                $this->report .= $this->uploadFile($file, $folderID, $service);
            }
        }
        else {
            $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/googleapi/oauth2callback.php';
            header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
        }
    }

    function uploadFile($fileName, $folderID, Google_Service_Drive $driveService) {
        $fileMetadata = new Google_Service_Drive_DriveFile(array(
                'name' => $fileName,
                'parents' => array($folderId)
        ));

        try {
            $content = file_get_contents($fileName);
            $file = $driveService->files->create($fileMetadata, array(
                    'data' => $content,
                    'mimeType' => 'application/x-gzip',
                    'uploadType' => 'multipart',
                    'fields' => 'id'));
            return "File '$fileName' uploaded with id '$file->id'" . PHP_EOL;
        }
        catch (Exception $exc) {
            return "Error working with file '$fileName':" . $exc->getMessage();
        }
    }
}

我该如何解决?

确保您具有该文件的有效权限 您必须将Permission角色设置为“ owner ”,并将角色设置为user (因为您是进行上传的角色)。

您可以在关于权限上阅读更多内容

暂无
暂无

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

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