Info:
- I'm using the PHP client library for Google API
- I've created a project in Google's Developer Console, for OAuth I use Service account as Application Type.
- I've used the code on pages https://developers.google.com/drive/v2/reference/files/insert#examples and https://developers.google.com/drive/v2/reference/permissions/insert#examples
I've made a short sample in which I upload a file to Google Drive using the credentials of the service account. Since the service account doesn't have a Drive UI (Google Drive API Upload returns File ID/Title but document does not exist in Drive), I've added permissions for my own account. This works fine. But when I open the file in Google Docs I don't see the content of the file I uploaded. Below is my code. In the file I want to upload the content is "Hello World!" but this is not present in the document on Google Drive. Any ideas on how to fix this?
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);