Php 如何使用Google Storage REST api删除包含文件的文件夹?
我正在尝试使用RESTAPI从Google存储中删除Php 如何使用Google Storage REST api删除包含文件的文件夹?,php,google-cloud-storage,Php,Google Cloud Storage,我正在尝试使用RESTAPI从Google存储中删除\u$folder$。到目前为止,我已经尝试了headerserver.com/testestset/*,headerserver.com/testestset,headerserver.com/testestset\u$folder$,但当文件夹中有任何文件时,这两种方法似乎都不起作用 到目前为止,我提出的唯一方法是在尝试删除\$folder$之前,先对\$folder$下的所有对象进行foreach,但是,这是非常低效的 在最糟糕的情况下:
\u$folder$
。到目前为止,我已经尝试了headerserver.com/testestset/*
,headerserver.com/testestset
,headerserver.com/testestset\u$folder$
,但当文件夹中有任何文件时,这两种方法似乎都不起作用
到目前为止,我提出的唯一方法是在尝试删除\$folder$
之前,先对\$folder$
下的所有对象进行foreach
,但是,这是非常低效的
在最糟糕的情况下:每个请求可以批处理/删除多个文件吗?不幸的是,除了删除目录或
\u$folder$
对象中的所有对象之外,没有其他方法了。已经4年了,他们仍然没有提供合适的API
对于仍然需要解决的人,这里有一个选择
此示例用于删除父文件夹、其嵌套文件夹及其所有内容
<?php
/**
* Delete nested folders for Google Cloud Storage
*/
class ClassName {
/** @var Google_Service_Storage $storageService */
public $storageService;
/** @var string $bucket */
public $bucket = '';
/**
* Remove an object
*
* @param string $objectPath
* @return boolean
*/
public function removeObject($objectPath) {
// validator
try {
if (!$this->storageService->objects->get($this->bucket, $objectPath)) {
// log error
return false;
}
} catch (Exception $ex) {
// leave this empty
}
// remove action
try {
$this->storageService->objects->delete($this->bucket, $objectPath);
} catch (Exception $ex) {
// log error
return false;
}
// log success
return true;
}
/**
* Remove the specified container
*
* @param string $path
* @return boolean
*/
public function removeContainer($path) {
$c = array();
$c['delimiter'] = '/';
if (!empty($path) && $path != '/') {
$c['prefix'] = $path;
}
$objects = null;
// validator
try {
$objects = $this->storageService->objects->listObjects($this->bucket, $c);
if (empty($objects)) {
if (!$this->storageService->objects->get($this->bucket, $path)) {
// log error
return false;
}
}
} catch (Exception $ex) {
// leave this empty
}
// remove action
try {
if (empty($objects)) {
$this->storageService->objects->delete($this->bucket, $path);
} else {
/**
* Process files first
*/
$files = $objects->getItems();
if (!empty($files)) {
foreach ($files as $file) {
$this->removeObject($file->getName());
}
}
/**
* And folders later
*/
$folders = $objects->getPrefixes();
if (!empty($folders)) {
foreach ($folders as $folder) {
$this->removeContainer($folder);
}
}
}
} catch (Exception $ex) {
// log error
return false;
}
// log success
return true;
}
}