0

我正在尝试使用 goolge drive api 的服务帐户将文件上传到“我的”中央 Google Drive。我从 Google 驱动器 API 获取示例代码,但是,当我运行代码时,确切地说,当使用 Google_DriveService 将文件插入驱动器时,Google chrome 显示“此网页不可用”。这是我的php代码:

<?php

require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";
session_start();

/**
 * Build and returns a Drive service object authorized with the service accounts.
 *
 * @return Google_DriveService service object.
 */
function buildService() {

    $DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
    $SERVICE_ACCOUNT_EMAIL = '<email>@developer.gserviceaccount.com';
    $SERVICE_ACCOUNT_PKCS12_FILE_PATH = '<filename>.p12';
  $key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
  $auth = new Google_AssertionCredentials(
      $SERVICE_ACCOUNT_EMAIL,
      array($DRIVE_SCOPE),
      $key);
  $client = new Google_Client();
  $client->setUseObjects(true);
  $client->setAssertionCredentials($auth);
  return new Google_DriveService($client);
}

function uploadFile($service, $mime, $src) {
    //Insert a file
    $file = new Google_DriveFile();
    $file->setMimeType($mime);
    $data = file_get_contents($src);

    try {
    //ERROR HERE: cannot insert (upload) file
        $createdFile = $service->files->insert($file,
            array(
                'data' => $data,
                'mimeType' => $mime,
                'convert' => true,
            )
        );

        return $createdFile;    
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }   
}

//test upload file to server
$service =buildService();
$mineType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
$path = "toupload.docx";
$file = uploadFile($service,$mineType, $path);

?>
4

0 回答 0