通过浏览器上传至Google Drive



我在使用服务/测试用户上传文件到谷歌驱动器时遇到了这个问题,但问题是我想完全跳过oauth。我想有一个上传表单为用户(例如教师)准备上传他们的文件到驱动器,而不需要登录/登录/验证身份等…我只需要用javascript来做这个。

我尝试使用。json工作。但我不认为我可以让它在浏览器上运行,因为我使用app.listen()与给定的端口,它运行在CMD上使用"node index.js(例如)"命令。所以我需要一个java脚本或php替代/片段。

要写入google drive帐户,您需要该帐户所有者的许可,因为它包含私人用户数据。

在客户端JavaScript的情况下,你唯一的选择是隐式流,它要求用户每次登录到应用程序时都要授权请求。

要考虑的服务器端备选方案。

如果您想考虑服务器端选项。我有几个备选方案给你。

首先,如果你要上传一个文件夹在谷歌驱动器上,你的开发人员控制。那么你可以使用一个服务账户。此服务帐户就像一个虚拟用户,您可以与服务帐户共享文件夹,服务帐户将授予其对文件夹的访问权限。然后在服务器端代码中,服务帐户可以在需要时访问它,而无需请求用户授权。

第二,如果你上传到你的用户驱动器帐户。您可以使用Oauth2并请求用户授权一次。在那个时候,你存储刷新令牌返回给你,然后当用户回来时,你可以使用刷新令牌请求一个新的访问令牌,并上传到他们的谷歌驱动器帐户。此解决方案只需要用户授权您的应用程序一次。

以上两种解决方案都可以使用node.js或php,它只需要是服务器端。

驱动器服务帐户php

下面是一个基本服务帐户授权示例。记住,一旦你创建了服务帐户,将服务帐户的电子邮件地址与你想要上传的google drive帐户上的文件夹共享。

如何创建Google Oauth2服务帐户凭据。

<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.n');
}
use GoogleServiceDrive;
const CREDENTIALS = 'C:DevelopmentFreeLanceGoogleSamplesCredentialsServiceAccountCred.json';
const SCOPES = [Google_Service_Drive::DRIVE_METADATA_READONLY];
printf("Service Account Access to google drive api.n");
// Create service account client, with drive scopes.
$client = new GoogleClient();
$client->setAuthConfig(CREDENTIALS);
$client->setScopes(SCOPES);
// Create Google Drive service
$service = new Drive($client);
// Print files that the service account has access to.
try {
$optParams = array(
'pageSize' => 10,
'fields' => 'files(id,name,mimeType)',
'q' => 'mimeType = "application/vnd.google-apps.folder" and "root" in parents',
'orderBy' => 'name'
);
$results = $service->files->listFiles($optParams);
$files = $results->getFiles();
if (empty($files)) {
$data = json_decode(file_get_contents(CREDENTIALS), true);
print "No files found.n";
printf("Please upload a file or share a file with the service account at (%s) ", $data["client_email"]);
} else {
print "Files:n";
foreach ($files as $file) {
$id = $file->id;
printf("%s - (%s) - (%s)n", $file->getId(), $file->getName(), $file->getMimeType());
}
}
} catch (Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' . $e->getMessage();
}

最新更新