如何使用 Google Drive API 上传我的 Drive (PHP) 中的文件?

Rav*_*ash 0 php google-drive-api

我想制作一个网页,其中会有一个文件输入框,用户上传的文件应该保存到我的谷歌驱动器中。

我如何使用 PHP 实现它?

我不想使用作曲家

我需要参考一篇有一些迹象的好文章

我在谷歌上查了一下,但我发现文章要写在别人的云端硬盘上,而不是我自己的。另外,我查看了 Drive API 文档,但我认为它对我来说太专业了!请告诉我如何制作一个简单的上传PHP页面。

zig*_*hka 13

使用 Google Drive API 上传到 Google Drive - 无需作曲家

将该功能与网站集成所需的条件:

  • 安装google-api-php-client
  • 安装Google_DriveService 客户端
  • 无论您如何将文件上传到 Google 云端硬盘 - 您都需要某种凭据来表明您有权访问相关云端硬盘(即您需要以自己的身份进行身份验证)。为此:
    • 如果尚未完成 - 设置(免费)Google Cloud 控制台。
    • 创建一个项目
    • 启用驱动器 API
    • 设置同意屏幕
    • APIs & Services -> Credentials+Create Credentials
    • 有几种可能性,在您的情况下,创建OAuth client ID和选择是有意义的Application type: Web Application
    • 使用表单指定您网站的 URLAuthorized JavaScript originsAuthorized redirect URIs
    • 创建客户端后 - 记下client IDclient secret

现在,您可以将 Google 的OAuth2 客户端身份验证示例Google Drive 服务对象的创建和Uploading to Google Drive放在一起,然后将其合并到PHP File Upload 中

将这些代码片段修补在一起可能如下所示:

表单.html

<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

上传.php

<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
//create a Google OAuth client
$client = new Google_Client();
$client->setClientId('YOUR CLIENT ID');
$client->setClientSecret('YOUR CLIENT SECRET');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
    FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
if(empty($_GET['code']))
{
    $client->authenticate();
}

if(!empty($_FILES["fileToUpload"]["name"]))
{
  $target_file=$_FILES["fileToUpload"]["name"];
  // Create the Drive service object
  $accessToken = $client->authenticate($_GET['code']);
  $client->setAccessToken($accessToken);
  $service = new Google_DriveService($client);
  // Create the file on your Google Drive
  $fileMetadata = new Google_Service_Drive_DriveFile(array(
    'name' => 'My file'));
  $content = file_get_contents($target_file);
  $mimeType=mime_content_type($target_file);
  $file = $driveService->files->create($fileMetadata, array(
    'data' => $content,
    'mimeType' => $mimeType,
    'fields' => 'id'));
  printf("File ID: %s\n", $file->id);
}
?>
Run Code Online (Sandbox Code Playgroud)