Javascript 通过API保存到谷歌硬盘
使用javascript或/和PHP并连接到(SDK),我希望允许用户将文件上载到自己的Google Drive帐户。示例按钮:Javascript 通过API保存到谷歌硬盘,javascript,php,google-api,google-drive-api,google-oauth,Javascript,Php,Google Api,Google Drive Api,Google Oauth,使用javascript或/和PHP并连接到(SDK),我希望允许用户将文件上载到自己的Google Drive帐户。示例按钮: <div class="save-to-google-drive" data-url="//example.com/path/to/filename.docx" data-filename="filename.docx" data-title="Title of file"> Upload to </div>
<div class="save-to-google-drive"
data-url="//example.com/path/to/filename.docx"
data-filename="filename.docx"
data-title="Title of file">
Upload to
</div>
上传到
当用户点击此按钮时,它应该上传到他们的Google Drive帐户
其目的是模拟按钮的行为 我建议您研究一下这个问题,虽然可以使用javascript来实现这一点,但我个人认为使用php会更容易
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'photo.jpg'));
$content = file_get_contents('files/photo.jpg');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart',
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
代码从
你需要进行身份验证我有一些示例代码
Oauth2CallBack.php
Oauth2Authentication.php
用法
require_once __DIR__ . '/vendor/autoload.php';
session_start();
require_once __DIR__ . '/Oauth2Authentication.php';
$_SESSION['mainScript'] = basename($_SERVER['PHP_SELF']); // Oauth2callback.php will return here.
$client = getGoogleClient();
$service = new Google_Service_Drive($client);
注意:然后将使用服务调用api。如果该问题符合条件,我将以400分奖励该问题。请将您的问题显示出来。您应该至少包括您遇到问题的代码的大纲(但最好是a),然后我们可以尝试帮助解决特定问题。您还应该阅读。如果您想要更新版本,那么您可以查看git项目,自述文件解释了如何使用它。我建议使用composer获取库。第一次运行它时,它会弹出请求验证并返回给您。可以在这里找到ReadMe for The this,它解释了如何设置开发人员控制台并正确设置脚本。我看到了问题所在。您上面的代码不正确,例如,您没有使用
oauth2callback.php
而是使用oauth2callback.php
,并且您缺少服务文件等。我已上载了所有github文件,我相信我已经授权了它。你能用相关代码更新你的答案并上传到硬盘吗?@DaImTo-Wow,一直在浏览你的git和可爱的作品!我也非常有兴趣看到工作代码上传文件到谷歌驱动器。也许您可以用一些相关的代码演示用户如何单击按钮并触发Google\u Service\u Drive\u DriveFile()
。。。您的文件中有自定义函数吗?尽管如此,这是一个很好的答案,并期待看到它的慷慨。然而,我担心的是,在考虑当前问题的目的时,它目前是不完整的。我认为您没有理解堆栈的意义,我们不是编码服务。我建议你试试这个。我给你的已经足够让它工作了。如果您有任何问题,请告诉我。
require_once __DIR__ . '/vendor/autoload.php';
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Initializes a client object.
* @return A google client object.
*/
function getGoogleClient() {
$client = getOauth2Client();
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Scopes will need to be changed depending upon the API's being accessed.
* Example: array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* @return A google client object.
*/
function buildClient(){
$client = new Google_Client();
$client->setAccessType("offline"); // offline access. Will result in a refresh token
$client->setIncludeGrantedScopes(true); // incremental auth
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope([YOUR SCOPES HERE]);
$client->setRedirectUri(getRedirectUri());
return $client;
}
/**
* Builds the redirect uri.
* Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
* Hostname and current server path are needed to redirect to oauth2callback.php
* @return A redirect uri.
*/
function getRedirectUri(){
//Building Redirect URI
$url = $_SERVER['REQUEST_URI']; //returns the current URL
if(strrpos($url, '?') > 0)
$url = substr($url, 0, strrpos($url, '?') ); // Removing any parameters.
$folder = substr($url, 0, strrpos($url, '/') ); // Removeing current file.
return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}
/**
* Authenticating to Google using Oauth2
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Returns a Google client with refresh token and access tokens set.
* If not authencated then we will redirect to request authencation.
* @return A google client object.
*/
function getOauth2Client() {
try {
$client = buildClient();
// Set the refresh token on the client.
if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
$client->refreshToken($_SESSION['refresh_token']);
}
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Refresh the access token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
return $client;
} else {
// We do not have access request access.
header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
}
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
require_once __DIR__ . '/vendor/autoload.php';
session_start();
require_once __DIR__ . '/Oauth2Authentication.php';
$_SESSION['mainScript'] = basename($_SERVER['PHP_SELF']); // Oauth2callback.php will return here.
$client = getGoogleClient();
$service = new Google_Service_Drive($client);