亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

PHP
明月笑刀無情 2023-11-05 15:40:12
我想制作一個網頁,其中將有一個文件輸入框,用戶上傳的文件應該保存到我的 Google Drive 中。如何使用PHP實現它?我不想使用 composer我需要參考一篇帶有一些跡象的好文章我在谷歌上查了一下,但我找到了在別人的云端硬盤上寫的文章,但不是我自己的。 此外,我還查看了Drive API文檔,但我認為它對我來說太專業了!請告訴我如何制作一個簡單的上傳PHP頁面。
查看完整描述

1 回答

?
德瑪西亞99

TA貢獻1770條經驗 獲得超3個贊

使用 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


<?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);

}

?>


查看完整回答
反對 回復 2023-11-05
  • 1 回答
  • 0 關注
  • 215 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號