我正在尝试将pdf上传到谷歌驱动器作为PHP中的服务帐户。
我在尝试上传时遇到浏览器错误:ERR_CONNECTION_RESET。
我从这里得到了代码: https://developers.google.com/drive/web/service-accounts#next_steps 和 https://developers.google.com/drive/v2/reference/files/insert
<?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();
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = 'xxx@developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'API Project-xxx.p12';
/**
* Build and returns a Drive service object authorized with the service accounts.
*
* @return Google_DriveService service object.
*/
function buildService() {
global $DRIVE_SCOPE, $SERVICE_ACCOUNT_EMAIL, $SERVICE_ACCOUNT_PKCS12_FILE_PATH;
$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);
}
/**
* Insert new file.
*
* @param Google_DriveService $service Drive API service instance.
* @param string $title Title of the file to insert, including the extension.
* @param string $description Description of the file to insert.
* @param string $parentId Parent folder's ID.
* @param string $mimeType MIME type of the file to insert.
* @param string $filename Filename of the file to insert.
* @return Google_DriveFile The file that was inserted. NULL is returned if an API error occurred.
*/
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) {
$file = new Google_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
$service=buildService();
$title='test';
$description='qqq';
$parentId='';
$mimeType='application/pdf';
$filename='doc.pdf';
insertFile($service, $title, $description, $parentId, $mimeType, $filename)
?>