如何使用服务帐户和PHP上传到Google Drive

发布于 2025-02-05 20:24:02 字数 2080 浏览 3 评论 0 原文

向下您可以看到我的代码,并将文件上传到我的Google驱动器。现在,我试图使用服务帐户让人们无需使用Google帐户即可将文件上传到我的Google驱动器(访问者将用他们的文件提交HTML表单,而我的应用程序将将该文件上传到我的驱动器)。但是我坚持下去。甚至找不到一个工作示例。有什么想法吗?

$client = new Google\Client();
$client->setAuthConfig('credentials.json');
$client->addScope(Google\Service\Drive::DRIVE);
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);

if (isset($_GET['code'])) {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $client->setAccessToken($token);

    // store in the session also
    $_SESSION['upload_token'] = $token;

    // redirect back to the example
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
if (!empty($_SESSION['upload_token'])) {
    $client->setAccessToken($_SESSION['upload_token']);
    if ($client->isAccessTokenExpired()) {
        unset($_SESSION['upload_token']);
    }
} else {
    $authUrl = $client->createAuthUrl();
}
echo $client->getAccessToken();
if ($_SERVER['REQUEST_METHOD'] == 'GET' && $client->getAccessToken()) {
    // We'll setup an empty 1MB file to upload.
    DEFINE("TESTFILE", 'test.jpg');
    if (!file_exists(TESTFILE)) {
        $fh = fopen(TESTFILE, 'w');
        fseek($fh, 1024 * 1024);
        fwrite($fh, "!", 1);
        fclose($fh);
    }

    // This is uploading a file directly, with no metadata associated.
    $file = new Google\Service\Drive\DriveFile();
    $service = new Google_Service_Drive($client);
    $file->setName("Hello World!");
    $result = $service->files->create(
        $file,
        [
            'data' => file_get_contents(TESTFILE),
            'mimeType' => 'application/octet-stream',
            'uploadType' => 'media'
        ]
    );
    $permissionService = new Google_Service_Drive_Permission();
    $permissionService->role = "reader";
    $permissionService->type = "anyone"; // anyone with the link can view the file
    $service->permissions->create($result->id, $permissionService);

Down you can see my code and it uploads files to my google drive. Now I am trying to use service account to let the people to upload files to my Google drive without their google accounts (Visitors will submit html form with their file and my app will upload that file to my drive ). But I am stuck with it. Can not find even just one working example. Any ideas?

$client = new Google\Client();
$client->setAuthConfig('credentials.json');
$client->addScope(Google\Service\Drive::DRIVE);
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);

if (isset($_GET['code'])) {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $client->setAccessToken($token);

    // store in the session also
    $_SESSION['upload_token'] = $token;

    // redirect back to the example
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
if (!empty($_SESSION['upload_token'])) {
    $client->setAccessToken($_SESSION['upload_token']);
    if ($client->isAccessTokenExpired()) {
        unset($_SESSION['upload_token']);
    }
} else {
    $authUrl = $client->createAuthUrl();
}
echo $client->getAccessToken();
if ($_SERVER['REQUEST_METHOD'] == 'GET' && $client->getAccessToken()) {
    // We'll setup an empty 1MB file to upload.
    DEFINE("TESTFILE", 'test.jpg');
    if (!file_exists(TESTFILE)) {
        $fh = fopen(TESTFILE, 'w');
        fseek($fh, 1024 * 1024);
        fwrite($fh, "!", 1);
        fclose($fh);
    }

    // This is uploading a file directly, with no metadata associated.
    $file = new Google\Service\Drive\DriveFile();
    $service = new Google_Service_Drive($client);
    $file->setName("Hello World!");
    $result = $service->files->create(
        $file,
        [
            'data' => file_get_contents(TESTFILE),
            'mimeType' => 'application/octet-stream',
            'uploadType' => 'media'
        ]
    );
    $permissionService = new Google_Service_Drive_Permission();
    $permissionService->role = "reader";
    $permissionService->type = "anyone"; // anyone with the link can view the file
    $service->permissions->create($result->id, $permissionService);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

您的好友蓝忘机已上羡 2025-02-12 20:24:02

以下代码将向您展示如何设置服务帐户授权。

请记住,尽管文件将上传到服务帐户驱动器帐户。如果您希望它们上传到您的个人驱动器帐户。您需要与服务帐户上的驱动器帐户上共享一个目录。尽管Web应用程序像其他任何用户一样,您可以使用服务帐户电子邮件地址来执行此操作。它的属性看起来像一封电子邮件。

您应该可以删除现在拥有的验证,然后使用此验证。但是,您需要将上传元数据中的父母设置为您想要填充到的目录的父母。

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');


/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}

/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed. 
 * array(Google_Service_Analytics::DRIVE)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {   
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(array(Google_Service_Analytics::DRIVE));
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

这样做会给您带来相同的服务对象。

$service = new Google_Service_Drive(getGoogleClient());

The following code will show you how to set up service account authorization.

Remember though the files will be uploaded to the service accounts drive account. If you want them uploaded to your personal drive account. You need to share a directory on your drive account with the service account. You do that though the web app like you would any other user, using the service account email address. Its the property that looks like an email.

You should just be able to remove the auth you have now and then use this. You will however need set the parents in the upload metadata to be that of that directory you want the fill uploaded to.

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');


/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}

/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed. 
 * array(Google_Service_Analytics::DRIVE)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {   
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(array(Google_Service_Analytics::DRIVE));
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

Doing something like this will then get you the same service object.

$service = new Google_Service_Drive(getGoogleClient());
染柒℉ 2025-02-12 20:24:02

You can use https://www.npmjs.com/package/drive-upload-service-account for this. It is a npm package which allows users to upload their files to the drive directly from server side using a service account.
It is well documented and hopefully the answer to your question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文