【问题标题】:upload file to google drive using php web service使用 php 网络服务将文件上传到谷歌驱动器
【发布时间】:2014-03-12 02:47:42
【问题描述】:

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

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

}

谢谢

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      最近更新 更多