的信息:
我做了一个简短的示例,我使用服务帐户的凭据将文件上传到Google云端硬盘。由于服务帐户没有云端硬盘用户界面(Google Drive API Upload returns File ID/Title but document does not exist in Drive),因此我已为自己的帐户添加了权限。这很好用。但是当我在Google文档中打开文件时,我看不到上传文件的内容。以下是我的代码。在我要上传的文件中,内容是" Hello World!"但Google Drive上的文档中没有此信息。关于如何解决这个问题的任何想法?
function insertFile($service, $title, $description, $parentId, $mimeType, $fileName) {
print "<br/>Uploading file...<br/>";
$file = new Google_Service_Drive_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($fileName);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType
));
$newFileId = $createdFile->getId();
// Give permission to my email so I can see the file in my Drive UI
$myEmail = "<mygmail>";
$userType = "user";
$userRole = "writer";
insertPermission($service, $newFileId, $myEmail, $userType, $userRole);
print "<br/>File uploaded successfully!";
downloadFile($service, $newFileId);
} catch (Exception $e) {
print "<br/>An error occurred: " . $e->getMessage();
}
}
function insertPermission($service, $fileId, $userToPermit, $typeOfUser, $role) {
$newPermission = new Google_Service_Drive_Permission();
$newPermission->setValue($userToPermit);
$newPermission->setType($typeOfUser);
$newPermission->setRole($role);
try {
return $service->permissions->insert($fileId, $newPermission);
} catch (Exception $e) {
print "<br/>Error occurred while attempting to permit " . $userToPermit . " to file.<br/>" . $e->getMessage();
}
return null;
}
$docTitle = "UploadTest4.txt";
$docMimeType = "text/plain";
$docToUpload = "document.txt";
insertFile($service, $docTitle, null, null, $docMimeType, $docToUpload);
答案 0 :(得分:0)
之前没有找过这篇文章,但我尝试了提供的解决方案,它对我有用(对于原始海报不够奇怪)。我不得不在插入请求中添加uploadType参数。
uploadType => 'media'