1 回答

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 ID
Application type: Web Application
使用格式指定網站的 URL,格式為 和
Authorized JavaScript origins
Authorized redirect URIs
創建客戶端后 - 記下和
client ID
client 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);
}
?>
- 1 回答
- 0 關注
- 215 瀏覽
添加回答
舉報