如何在 Google 云存储 (PHP API) 中重命名或移动文件

How to rename or move a file in Google Cloud Storage (PHP API)

我目前正在尝试重命名 and/or 将一个云存储文件移动到另一个 name/position,但我无法让它工作。我使用 https://github.com/google/google-api-php-client 作为客户端,上传工作正常:

...
$storageService = new \Google_Service_Storage( $client )
$file = new \Google_Service_Storage_StorageObject()
$file->setName( 'test.txt' );
$storageService->objects->insert(
   $bucketName,
    $file,
    array(
        'name'          => $filename,
        'data'          => file_get_contents( $somefile )
    )
);
...

所以我尝试通过 $storageObject->objects->update() 方法更改文件名,但我找不到任何相关文档。我使用 $storageService->objects->get( $bucketName, $fileName ) 来获取我想重命名的特定文件(使用 $file->setName()),但似乎我无法将文件传递给对象- >更新功能。我做错了吗?

好吧,看来我不能直接重命名文件(如果我错了请指正),我只能更新元数据。我设法通过将文件复制到新的 filename/destination 然后删除旧文件来让它工作。为此,我成功地使用了 $storageService->objects->copy 和 $storageService->objects->delete 。这感觉不对,但至少有效。

由于 google 没有很好地记录,这里有一个基本示例:

//RENAME FILE ON GOOGLE CLOUD STORAGE (GCS)

//Get client and auth token (might vary depending on the way you connect to gcs – here with laravel framework facade)
//DOC: https://cloud.google.com/storage/docs/json_api/v1/json-api-php-samples
//DOC: https://developers.google.com/api-client-library/php/auth/service-accounts
//Laravel Client: https://github.com/pulkitjalan/google-apiclient 
//Get google client
$gc = \Google::getClient();
//Get auth token if it is not valid/not there yet
if($gc->isAccessTokenExpired())
    $gc->getAuth()->refreshTokenWithAssertion();
//Get google cloud storage service with the client
$gcStorageO = new \Google_Service_Storage($gc);

//GET object at old position ($path)
//DOC: https://cloud.google.com/storage/docs/json_api/v1/objects/get
$oldObj = $gcStorageO->objects->get($bucket, $path);

//COPY desired object from old position ($path) to new position ($newpath)
//DOC: https://cloud.google.com/storage/docs/json_api/v1/objects/copy
$gcStorageO->objects->copy(
    $bucket, $path, 
    $bucket, $newpath,
    $oldObj
);

//DELETE old object ($path)
//DOC: https://cloud.google.com/storage/docs/json_api/v1/objects/delete
$gcStorageO->objects->delete($bucket, $path);

我发现将 gcutils 与 PHP 结合使用时,您几乎可以在 App Engine 上执行每个 php 文件命令。复制、删除、检查文件是否存在。

if(file_exists("gs://$bucket/{$folder}/$old_temp_file")){

        $old_path = "gs://$bucket/{$folder}/$old_temp_file";
        $new_permanent_path = "gs://$bucket/{$folder}/$new_permanent_file";

        copy($old_path, $new_permanent_path);  

        unlink($old_path);

    }