使用Php在Google云端硬盘中上传文件

时间:2014-09-30 06:39:18

标签: php google-drive-api

我正在尝试使用Php在Google云端硬盘中上传文件但我收到了错误

  

致命错误:未捕获的异常' Google_Service_Exception'消息'错误调用POST https://www.googleapis.com/upload/drive/v2/files?uploadType=media :( 401)需要登录'在C:\ xampp \ htdocs \ Testing \ src \ Google \ Http \ REST.php:79

这是我的代码:     

DEFINE("TESTFILE", 'testfile-small.txt');//Creating a file
if (true || !file_exists(TESTFILE)) {
    $fh = fopen(TESTFILE, 'w');
    echo "File Created";
    fseek($fh, 1024 * 1024);
    fwrite($fh, "!", 1);
    fclose($fh);
}
//Setting the Authentication Properties
$client_id = 'x-x-x-';      //These properties generated using GoogleApisConsole
$client_secret = 'x-x-x-';
$redirect_uri = 'x-x-x ';
 $client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
//$client->setDeveloperKey('AIzaSyAMOwFvprof_tCGdfiaeoUoYI5BfgGyO7I');
$client->setApplicationName("My Application");
$client->addScope("https://www.googleapis.com/auth/drive.file");//Adding Scope

$service = new Google_Service_Drive($client);
//Checking for User Session
if (isset($_REQUEST['logout'])) {
    echo "In first if";
    unset($_SESSION['upload_token']);
}
if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['upload_token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['upload_token']) && $_SESSION['upload_token']) {
    $client->setAccessToken($_SESSION['upload_token']);
    echo "In second if";
    if ($client->isAccessTokenExpired()) {
        echo "In third if";
        unset($_SESSION['upload_token']);
    }
} else {
    echo "In else";
    $authUrl = $client->createAuthUrl();
}

    // This is uploading a file directly, with no metadata associated.
//if ($client->getAccessToken()) {
       echo "Now i can send file";
    // This is uploading a file directly, with no metadata associated.
    $file = new Google_Service_Drive_DriveFile();
    echo "First Step";
    $result = $service->files->insert(
            $file,
            array(
                    'data' => file_get_contents(TESTFILE),
                    'mimeType' => 'application/octet-stream',
                    'uploadType' => 'media'
            )
    );

    // Now lets try and send the metadata as well using multipart!
    $file = new Google_Service_Drive_DriveFile();
    Echo "last problem";
    $file->setTitle("Hello World!");
    $result2 = $service->files->insert(
            $file,
            array(
                    'data' => file_get_contents(TESTFILE),
                    'mimeType' => 'application/octet-stream',
                    'uploadType' => 'multipart'
            )
    );
//}
echo ($client->getAccessToken());
echo "File Upload - Uploading a small file";

?>

请帮帮我。

0 个答案:

没有答案