如何在谷歌驱动器v3 PHP中更新文件


How to update file in google drive v3 PHP

我似乎无法使用以下代码更新谷歌云端硬盘中的文件,一切正常,但文件保持不变?我正在使用 v3 api。

 function updateFile($service, $fileId, $data) {
        try {
            $emptyFile = new Google_Service_Drive_DriveFile();
            $file = $service->files->get($fileId);
            $service->files->update($fileId, $emptyFile, array(
                'data' => $data,
                'mimeType' => 'text/csv',
                'uploadType' => 'multipart'
            ));
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }

我设法做到了,你必须把空文件作为第二个参数,不知道为什么,但这篇文章对我帮助很大: 谷歌驱动器API v3迁移

这是最终解决方案:

function updateFile($service, $fileId, $data) {
        try {
            $emptyFile = new Google_Service_Drive_DriveFile();
            $service->files->update($fileId, $emptyFile, array(
                'data' => $data,
                'mimeType' => 'text/csv',
                'uploadType' => 'multipart'
            ));
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }

其中$fileId是您正在更新的文件,数据是您正在更新文件的新内容。

在此之后不要忘记刷新谷歌驱动器,因为它的预览没有改变,我损失了一个小时:/。希望这有帮助。

 function updateFile($fileId,$newDescription){
        try {    
            // First retrieve the file from the API. 
            $emptyFile = new Google_Service_Drive_DriveFile();
            // File's new metadata.   
            $emptyFile->setDescription($newDescription);
            // Send the request to the API.
            $driveService->files->update($fileId, $emptyFile, array());
            print 'success';
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }//end update

如果您希望像描述一样更新员工,该方法是必不可少的。我从 v2 复制了这个想法。

// File's new metadata.
$file->setTitle($newTitle);
$file->setDescription($newDescription);
$file->setMimeType($newMimeType);

注意:您还必须确保更新功能的3个参数是一个数组也如其他有用的答案中所述;确保您刷新谷歌云端硬盘进行检查