Google 驱动器 API - 上传和导出文件

Google Drive API - upload and export file

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

Fatal error: Uncaught exception 'Google_Service_Exception, "message": "Insufficient Permission"

权限问题,不知道怎么解决。 这是我使用的代码:

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 行抛出错误

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

Google_Service_Drive::DRIVE_METADATA_READONLY

这为您提供了只读访问权限。以下是 Google 驱动器 api 可用的 scopes 的列表。

https://www.googleapis.com/auth/drive View and manage the files in your Google Drive

https://www.googleapis.com/auth/drive.appdata View and manage its own configuration data in your Google Drive

https://www.googleapis.com/auth/drive.file View and manage Google Drive files and folders that you have opened or created with this app

https://www.googleapis.com/auth/drive.metadata View and manage metadata of files in your Google Drive

https://www.googleapis.com/auth/drive.metadata.readonly View metadata for files in your Google Drive

https://www.googleapis.com/auth/drive.photos.readonly View the photos, videos and albums in your Google Photos

https://www.googleapis.com/auth/drive.readonly View the files in your Google Drive

https://www.googleapis.com/auth/drive.scripts Modify your Google Apps Script scripts' behavior

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

我的东西工作了。我认为范围的定义有些问题。顺便说一句,我找到了一些非常有帮助的示例 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 类型,参考:HERE and HERE