上传文件的内容缺少Google Drive


Content of uploaded file missing Google Drive

信息:

  • 我正在使用Google API的PHP客户端库
  • 我在谷歌的开发者控制台中创建了一个项目,对于OAuth,我使用服务帐户作为应用程序类型
  • 我在页面上使用了代码https://developers.google.com/drive/v2/reference/files/insert#examples和https://developers.google.com/drive/v2/reference/permissions/insert#examples

我做了一个简短的示例,其中我使用服务帐户的凭据将文件上传到Google Drive。由于服务帐户没有驱动器UI(Google Drive API Upload返回文件ID/Title,但驱动器中不存在文档),我为自己的帐户添加了权限。这很好用。但当我在谷歌文档中打开文件时,我看不到我上传的文件的内容。下面是我的代码。在我想上传的文件中,内容是"Hello World!",但谷歌硬盘上的文档中没有这一点。关于如何解决这个问题有什么想法吗?

        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);

以前没有找到这篇文章,但我尝试了提供的解决方案,它对我来说很有效(奇怪的是,对于最初的海报来说不是这样)。我不得不在插入请求中添加一个uploadType参数。

uploadType => 'media'

使用google drive php-api 上传的带有空内容的文件