如何更新 google 驱动器 v3 PHP 中的文件

How to update file in google drive v3 PHP

我似乎无法使用以下代码更新 google 驱动器中的文件,一切正常但文件保持不变?我正在使用 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();
        }
    }

我设法做到了,你必须将空文件作为第二个参数,不知道为什么,但是这个 post 对我帮助很大:

这是最终解决方案:

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 是您正在更新的文件,data 是您正在更新文件的新内容。

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

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

NB: 另外你必须保证update函数的3个参数是一个数组 也如其他有用的答案所述;确保刷新 google 驱动器以检查