无法通过Google API将文件上传到Google云端硬盘
问题描述:
当我尝试通过Google API上传文件到Google云端硬盘时(https://github.com/google/google-api-php-client),我收到错误“权限不足”(读取的文件没有任何问题)。这里是代码示例:无法通过Google API将文件上传到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();
}
}
}
我该如何解决它?
确保您使用验证用户可以访问“FolderIdFromGoogleDrive – DaImTo
我只使用一个用户和该用户可以创建内部文件‘通过谷歌驱动的网站FolderIdFromGoogleDrive’。 – Varro
显然,如果你得到“权限不足”,试着做一个file.list,并确保该文件夹出现给用户,如果出现然后重新认证用户,你必须使用差别范围认证一次,然后 – DaImTo