上传文件的内容丢失 Google 驱动器

Content of uploaded file missing Google Drive

信息:

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

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

之前没有找到这个 post,但我尝试了提供的解决方案,它对我有用(奇怪的是,原来的 poster 却没有)。我必须在插入请求中添加一个 uploadType 参数。

uploadType => 'media'

file uploaded with empty content using google drive php api