使用php web服务将文件上传到谷歌驱动器

时间:2014-02-12 11:12:42

标签: php google-drive-api google-drive-realtime-api

我正在使用谷歌驱动器文件上传代码。以下代码在浏览器中运行正确。但是,如果我尝试这样做,我们错误为:fgets()期望参数1是资源,给定字符串 我尝试了很多解决方案,但它不起作用。请指导我如何使用此代码将Web服务上传到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); 

}

由于

1 个答案:

答案 0 :(得分:0)

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上传/下载....

相关问题