簡體   English   中英

使用php Web服務將文件上傳到Google驅動器

[英]upload file to google drive using php web service

我正在使用Google驅動器文件上傳代碼。 以下代碼在瀏覽器中正確運行。 但是,如果我嘗試執行此操作,則會出錯,因為:fgets()期望參數1為資源,給定字符串,因為我嘗試了許多解決方案,但無法正常工作。 請指導我如何使用此代碼進行網絡服務將文件上傳到Google驅動器。

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';



function uploadFile()
{

$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('**********************');
$client->setClientSecret('*********');
$client->setRedirectUri('*********');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));


if(!defined("STDIN")) define("STDIN", "fopen('php://stdin','r')");

$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();

//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
//$authCode = trim(file_get_contents(STDIN));



// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);

//Insert a file
$file = new Google_DriveFile();
$file->setTitle('Test document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');

$data = file_get_contents('upload.txt');

$createdFile = $service->files->insert($file, array(
      'data' => $data,
      'mimeType' => 'text/plain',
    ));

print_r($createdFile); 

}

謝謝

STDIN是一個命令行指令,它不是直接有效的php語句..我所做的是:

$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('**********************');
$client->setClientSecret('*********');
$client->setRedirectUri('*********');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));

$authUrl = $client->createAuthUrl();
print $authurl

$authCode = ''; // insert the verification code that you get after going to url in $authurl
file_put_contents('token.json', $client->authenticate($authCode));

執行完這些后,您將在json文件token.json中獲取身份驗證信息...並且您可以使用以下內容上傳...:

$service = new Google_DriveService($client);

$client->setAccessToken(file_get_contents('token.json'));

//Insert a file 
    ..... // rest the same

一旦獲取json,就不要再運行頂級代碼了……每次都使用token.json上傳/下載...。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM