如何使用 Google Drive API 在我的云端硬盘 (PHP) 中上传文件?

我想制作一个网页,其中将有一个文件输入框,用户上传的文件应该保存到我的 Google Drive 中。

如何使用PHP实现它?

我不想使用 composer

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

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


明月笑刀无情
浏览 95回答 1
1回答

德玛西亚99

使用 Google Drive API 上传到 Google Drive - 不带 composer将该功能与网站集成所需的条件:安装 google-api-php-client安装 Google_DriveService 客户端无论您如何将文件上传到 Google 云端硬盘 - 您都需要某种凭据来表明您有权访问相关云端硬盘(也就是说,您需要以自己的身份进行身份验证)。为此:如果尚未完成,请(免费)设置 Google Cloud 控制台。创建项目。启用 Drive API。设置同意屏幕。转到 和APIs & Services -> Credentials+Create Credentials有几种可能性,就您而言,创建一个并选择是有意义的OAuth client IDApplication type: Web Application使用格式指定网站的 URL,格式为 和Authorized JavaScript originsAuthorized redirect URIs创建客户端后 - 记下和client IDclient secret现在,您可以将 Google 的示例放在一起,以便使用 OAuth2 客户端进行身份验证,创建 Google Drive 服务对象并上传到 Google Drive,然后将其合并到 PHP 文件上传中。将这些代码片段修补在一起可能如下所示:表单.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>上传.php<?phprequire_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);}?>
打开App,查看更多内容
随时随地看视频慕课网APP