我正试图上传一个图像到谷歌驱动器的光学字符识别(OCR)。这是我的密码:
require_once('vendor/autoload.php');
// Initialize Google Client
$client_email = 'xxxxxx@yyyyy.iam.gserviceaccount.com';
$private_key = file_get_contents('key.p12');
$scopes = array(
'https://www.googleapis.com/auth/drive.file'
);
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
// Initialize Google Drive service
$service = new Google_Service_Drive($client);
// Upload File
$file = new Google_Service_Drive_DriveFile();
$file->setName('Test Image for OCR');
$file->setDescription('Test Image for OCR');
$file->setMimeType('image/jpeg');
try {
$data = file_get_contents($filename);
$createdFile = $service->files->create($file, array(
'data' => $data,
'mimeType' => 'image/jpeg',
));
var_dump($createdFile);
// ===========
// So, what's next?
// ===========
} catch(Exception $e) {
echo 'Error occurred: ' . $e->getMessage();
}以上代码运行时没有错误,$createdFile是Google_Service_Drive_DriveFile对象形式的有效资源。
问题:
create()函数不返回错误。然而,我看不到文件被上传到我的谷歌驱动器。不应该上传到Google的根文件夹吗?ocrLanguage的参数。我应该把它放在哪里,如何获得结果?提前谢谢。
更新 var_dump()的结果如下:
object(Google_Service_Drive_DriveFile)#18 (55) {
["collection_key":protected]=>
string(6) "spaces"
["internal_gapi_mappings":protected]=>
array(0) {
}
["appProperties"]=>
NULL
["capabilitiesType":protected]=>
string(42) "Google_Service_Drive_DriveFileCapabilities"
["capabilitiesDataType":protected]=>
string(0) ""
["contentHintsType":protected]=>
string(42) "Google_Service_Drive_DriveFileContentHints"
["contentHintsDataType":protected]=>
string(0) ""
["createdTime"]=>
NULL
["description"]=>
NULL
["explicitlyTrashed"]=>
NULL
["fileExtension"]=>
NULL
["folderColorRgb"]=>
NULL
["fullFileExtension"]=>
NULL
["headRevisionId"]=>
NULL
["iconLink"]=>
NULL
["id"]=>
string(28) "0B_XXXXX1yjq7dENaQWp4ckZoRk0"
["imageMediaMetadataType":protected]=>
string(48) "Google_Service_Drive_DriveFileImageMediaMetadata"
["imageMediaMetadataDataType":protected]=>
string(0) ""
["kind"]=>
string(10) "drive#file"
["lastModifyingUserType":protected]=>
string(25) "Google_Service_Drive_User"
["lastModifyingUserDataType":protected]=>
string(0) ""
["md5Checksum"]=>
NULL
["mimeType"]=>
string(10) "image/jpeg"
["modifiedByMeTime"]=>
NULL
["modifiedTime"]=>
NULL
["name"]=>
string(18) "Test Image for OCR"
["originalFilename"]=>
NULL
["ownedByMe"]=>
NULL
["ownersType":protected]=>
string(25) "Google_Service_Drive_User"
["ownersDataType":protected]=>
string(5) "array"
["parents"]=>
NULL
["permissionsType":protected]=>
string(31) "Google_Service_Drive_Permission"
["permissionsDataType":protected]=>
string(5) "array"
["properties"]=>
NULL
["quotaBytesUsed"]=>
NULL
["shared"]=>
NULL
["sharedWithMeTime"]=>
NULL
["sharingUserType":protected]=>
string(25) "Google_Service_Drive_User"
["sharingUserDataType":protected]=>
string(0) ""
["size"]=>
NULL
["spaces"]=>
NULL
["starred"]=>
NULL
["thumbnailLink"]=>
NULL
["trashed"]=>
NULL
["version"]=>
NULL
["videoMediaMetadataType":protected]=>
string(48) "Google_Service_Drive_DriveFileVideoMediaMetadata"
["videoMediaMetadataDataType":protected]=>
string(0) ""
["viewedByMe"]=>
NULL
["viewedByMeTime"]=>
NULL
["viewersCanCopyContent"]=>
NULL
["webContentLink"]=>
NULL
["webViewLink"]=>
NULL
["writersCanShare"]=>
NULL
["modelData":protected]=>
array(0) {
}
["processed":protected]=>
array(0) {
}
}该文件可以通过$service->files->get($file_id);获得,但它在我的Google中是不可见的。返回的对象也不包含任何有用的内容。
发布于 2016-03-07 10:13:17
服务帐户不是更像一个虚拟用户吗?它有自己的驱动器帐户。
如果你想上传到你的个人帐户。获取服务帐户的电子邮件地址,并分享它在您的个人驱动器帐户目录。就像您希望与任何其他用户共享一个目录或文件一样。
然后,您需要找出目录id,我找到的唯一方法是让服务帐户执行files.list,以获得它现在可以访问的所有内容的列表。一旦找到目录id或父id,就可以将上面的代码更改为
'data' => $data,
'mimeType' => 'image/jpeg',
'parents' => 'the directory id'我认为,从您的代码的外观来看,您使用的是V3 api,我没有时间使用它。'parents' => 'the directory id' <如果它不起作用,让我知道,我会搜索一下,找出如何将家长传递给v3。
选项nr 2:
另一个选项是服务帐户与您共享它的文件夹,然后您可以访问它的驱动器帐户,并且您将能够在您的web版本的驱动器中看到该文件夹。再次搜索权限,我认为您正在使用V3,我还没有看过它。差异在于数据存储的位置和存储对谁的影响。
发布于 2016-05-05 10:11:33
我刚在V3找到了去OCR的路。
看起来第二步不适用于"appDataFolder“。
UserCredential credential = null;
try
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new Uri("ms-appx:///Assets/client_secret.json"),
new[] { DriveService.Scope.DriveFile }, "user", CancellationToken.None);
}
catch (AggregateException ex)
{
Debug.Write("Credential failed, " + ex.Message);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "TestApp",
});
// Create folder
var folderMetadata = new Google.Apis.Drive.v3.Data.File();
folderMetadata.Name = "NewFolder";
folderMetadata.MimeType = "application/vnd.google-apps.folder";
var request = service.Files.Create(folderMetadata);
request.Fields = "id";
var folder = request.Execute();
Debug.WriteLine("Folder ID: " + folder.Id);
// Upload the image file
var fileMetadata = new Google.Apis.Drive.v3.Data.File();
fileMetadata.Name = inputFile.Name;
fileMetadata.Parents = new List<string> { folder.Id };
FilesResource.CreateMediaUpload requestUpload;
using (var stream = new System.IO.FileStream(inputFile.Path, System.IO.FileMode.Open))
{
requestUpload = service.Files.Create(fileMetadata, stream, "image/jpeg");
requestUpload.Fields = "id";
requestUpload.Upload();
}
var imgFile = requestUpload.ResponseBody;
Debug.WriteLine("File ID: " + imgFile.Id);
// Copy image and paste as document
var textMetadata = new Google.Apis.Drive.v3.Data.File();
textMetadata.Name = inputFile.Name;
textMetadata.Parents = new List<string> { folderId };
textMetadata.MimeType = "application/vnd.google-apps.document";
FilesResource.CopyRequest requestCopy = service.Files.Copy(textMetadata, imgFile.Id);
requestCopy.Fields = "id";
requestCopy.OcrLanguage = "zh";
var textFile = requestCopy.Execute();
// Now we export document as plain text
FilesResource.ExportRequest requestExport = service.Files.Export(textFile.Id, "text/plain");
string output = requestExport.Execute();发布于 2016-03-08 05:20:42
不要使用服务帐户。如果您想上载到您自己的帐户,那么您只需为您的帐户获取适当的访问令牌即可。使用中间帐户使用共享文件夹非常难看(imho)。
https://stackoverflow.com/questions/35837456
复制相似问题