Google Drive API - 上传和导出文件

时间:2017-05-11 06:51:54

标签: php google-api google-drive-api google-oauth google-api-php-client

我需要通过Google云端硬盘上传文件,然后将其导出为不同的格式。例如,上传DOCX并将其导出为PDF。我一直在关注REST快速入门和上传文件指南。执行代码后,我收到错误:

  

致命错误:未捕获的异常'Google_Service_Exception,“message”:   “权限不足”

这是权限问题,但我不知道如何修复它。 这是我使用的代码:

date_default_timezone_set('Europe/Sofia');

require_once __DIR__ . '/vendor/autoload.php';

define('APPLICATION_NAME', 'Drive API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-php-quickstart.json
define('SCOPES', implode(' ', array(
  Google_Service_Drive::DRIVE_METADATA_READONLY)
));
//i've tried to change the scope to ::DRIVE, but still get the same error

if (php_sapi_name() != 'cli') {
  throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfig(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }
  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);

// Print the names and IDs for up to 10 files.
$optParams = array(
  'pageSize' => 10,
  'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);

if (count($results->getFiles()) == 0) {
  print "No files found.\n";
} else {
  print "Files:\n";
  foreach ($results->getFiles() as $file) {
    printf("%s  FILE_ID(%s)\n", $file->getName(), $file->getId());
  }
}


//The error I get is in this block:

$fileMetadata = new Google_Service_Drive_DriveFile(array(
  'name' => 'photo.jpg'));
$content = file_get_contents('photo.jpg');
$file = $service->files->create($fileMetadata, array(
  'data' => $content,
  'mimeType' => 'image/jpeg',
  'uploadType' => 'multipart',
  'fields' => 'id'));
printf("File ID: %s\n", $file->id);

编辑:忘记提及代码工作直到最后一个块,它成功列出文件,然后在最后10行抛出错误

2 个答案:

答案 0 :(得分:3)

范围定义您请求用户的访问范围。您已使用以下权限对代码进行身份验证。

  

Google_Service_Drive :: DRIVE_METADATA_READONLY

这为您提供只读访问权限。以下是适用于Google云端硬盘API的scopes列表。

  

https://www.googleapis.com/auth/drive查看和管理Google云端硬盘中的文件

     

https://www.googleapis.com/auth/drive.appdata在您的Google云端硬盘中查看和管理自己的配置数据

     

https://www.googleapis.com/auth/drive.file查看和管理您使用此应用打开或创建的Google云端硬盘文件和文件夹

     

https://www.googleapis.com/auth/drive.metadata查看和管理Google云端硬盘中文件的元数据

     

https://www.googleapis.com/auth/drive.metadata.readonly查看Google云端硬盘中文件的元数据

     

https://www.googleapis.com/auth/drive.photos.readonly查看Google相册中的照片,视频和相册

     

https://www.googleapis.com/auth/drive.readonly查看Google云端硬盘中的文件

     

https://www.googleapis.com/auth/drive.scripts修改您的Google Apps脚本脚本行为

我可能会选择第一个https://www.googleapis.com/auth/drive.file。我只在这里猜测,但对于PHP,它可能类似于Google_Service_Drive::DRIVE_FILE

答案 1 :(得分:1)

我得到了工作。我认为范围的定义有一些东西。 BTW我发现了一些非常有用的例子HERE 工作代码是:

<?php
date_default_timezone_set('Europe/Sofia');
include_once __DIR__ . '/../vendor/autoload.php';
include_once "templates/base.php";
echo pageHeader("File Upload - Uploading a simple file");
/*************************************************
 * Ensure you've downloaded your oauth credentials
 ************************************************/
if (!$oauth_credentials = getOAuthCredentialsFile()) {
  echo missingOAuth2CredentialsWarning();
  return;
}
/************************************************
 * The redirect URI is to the current page, e.g:
 * http://localhost:8080/simple-file-upload.php
 ************************************************/
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->setAuthConfig($oauth_credentials);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);
// add "?logout" to the URL to remove a token from the session
if (isset($_REQUEST['logout'])) {
  unset($_SESSION['upload_token']);
}
/************************************************
 * If we have a code back from the OAuth 2.0 flow,
 * we need to exchange that with the
 * Google_Client::fetchAccessTokenWithAuthCode()
 * function. We store the resultant access token
 * bundle in the session, and redirect to ourself.
 ************************************************/
if (isset($_GET['code'])) {
  $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
  $client->setAccessToken($token);
  // store in the session also
  $_SESSION['upload_token'] = $token;
  // redirect back to the example
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
// set the access token as part of the client
if (!empty($_SESSION['upload_token'])) {
  $client->setAccessToken($_SESSION['upload_token']);
  if ($client->isAccessTokenExpired()) {
    unset($_SESSION['upload_token']);
  }
} else {
  $authUrl = $client->createAuthUrl();
}
/************************************************
 * If we're signed in then lets try to upload our
 * file. For larger files, see fileupload.php.
 ************************************************/
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $client->getAccessToken()) {

// CREATE A NEW FILE
  $file = new Google_Service_Drive_DriveFile(array(
    'name' => 'sample',
    'mimeType' => 'application/vnd.google-apps.presentation'
  ));
  $pptx = file_get_contents("sample.docx"); // read power point pptx file
  //declare opts params
  $optParams = array(
    'uploadType' => 'multipart',
    'data' => $pptx,
    'mimeType' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  );
  //import pptx file as a Google Slide presentation
  $createdFile = $service->files->create($file, $optParams);
  //print google slides id
  //print "File id: ".$createdFile->id;

  $optParams2 = array(
    'fileId' => $createdFile->id,
    'mimeType' => 'application/pdf'
  );


  $response = $service->files->export($createdFile->id, 'application/pdf', array(
  'alt' => 'media' ));
//print_r($response);
  $content = $response->getBody()->getContents();
///rint_r($content);

$data = $content;
file_put_contents('test_ppt.pdf',$data);

}
?>

<div class="box">
<?php if (isset($authUrl)): ?>
  <div class="request">
    <a class='login' href='<?= $authUrl ?>'>Connect Me!</a>
  </div>
<?php elseif($_SERVER['REQUEST_METHOD'] == 'POST'): ?>
  <div class="shortened">
    <p>Your call was successful! Check your drive for the following files:</p>
    <ul>


    </ul>
  </div>
<?php else: ?>
  <form method="POST">
    <input type="submit" value="Click here to upload two small (1MB) test files" />
  </form>
<?php endif ?>
</div>

<?= pageFooter(__FILE__) ?>

如果您想转换为其他格式,只需按照引用更改Mime类型:HEREHERE