[英]Uploading the files to same google drive using php
我想知道是否有任何方法可以使用 php 将文件直接上传到我们自己的 Google 驱动器,目前我正在使用这样的方法。
$drive = new Google_Client();
$drive->setClientId($client_id);
$drive->setClientSecret($client_secret);
$drive->setRedirectUri($redirect_uri);
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$_GET['code'] = 'ya2-------------------------OZXiA';
//file_put_contents('token.json', $drive->authenticate());
$drive->setAccessToken(file_get_contents('token.json'));
$doc = new Google_DriveFile();
$doc->setTitle('Test Document');
$doc->setDescription('Test description');
$doc->setMimeType('text/plain');
$content = file_get_contents('/assets/new--detils.txt');
$output = $gdrive->files->insert($doc, array(
'data' => $content,
'mimeType' => 'text/plain',
));
print_r($output);
但这显示了一个错误
致命错误:未捕获的异常Google_AuthException
带有消息“获取 OAuth2 访问令牌时出错,消息: /var/www/path/src/auth/Google_OAuth2.php:115
: Google_AuthException
“invalid_grant”
在这里,我使用为该应用程序生成的$_GET['code'] = 'ya2-------------------------OZXiA'
,
任何人都可以提出一种方法来做到这一点,在此先感谢。
不确定它是否有帮助,但我通过谷歌代码发现了这个......
“当您尝试使用相同的授权代码时,您将收到 invalid_grant 错误。”
我在这里找到它: https : //code.google.com/p/google-api-php-client/issues/detail?id=94
不知道这对你有没有帮助...
还找到了本教程: http : //25labs.com/tutorial-implementing-google-api-using-oauth-2-0-in-php/
$drive = new Google_Client();
$drive->setClientId($client_id);
$drive->setClientSecret($client_secret);
$drive->setRedirectUri($redirect_uri);
**$drive->setAccessType('offline');**
$authUrl = $client->createAuthUrl();
echo $authUrl;
现在转到 auth url 并获取刷新令牌和其他内容。 确保这是您第一次请求许可,否则您将无法获得刷新令牌,这是将来制作 authtoken 所必需的。 如果您已经授予权限,只需转到您的 google 帐户并撤销该应用程序的权限。 这也是您要重定向的文件中应该包含的内容。
$tokeninfo = $drive->getAccessToken();
print_r($tokeninfo);
现在将令牌信息保存在“token.json”之类的文件中。
现在返回到包含上传代码的原始文件。
$drive = new Google_Client();
$drive->setClientId($client_id);
$drive->setClientSecret($client_secret);
$drive->setRedirectUri($redirect_uri);
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$drive->setAccessType('offline');
$service = new Google_Service_Drive($drive);
$refreshToken = "Your refresh token";
/* get it from token.json and it will look some like this 1**\/**asasfasfsfsd
remove the \ since this is actually json encoded.*/
$tokens = file_get_contents(TOKEN); /*TOKEN = the token.json file*/
$drive->setAccessToken($tokens);
if ($drive->isAccessTokenExpired()) {
$drive->refreshToken($refreshToken);
file_put_contents(TOKEN,$drive->getAccessToken());
}
Now you have done the authentication and just need to upload the file.
if ($drive->getAccessToken()) {
$file = new Google_Service_Drive_DriveFile();
$file->title ="the file name";
/*the upload code can be found in the examples*/
}
注意您上传的文件不能被其他人下载,需要设置googlepermissions才能共享文件。 如果您需要编码以添加权限,只需发表评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.