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