我正在 Google Cloud Storage 存储桶下的 Picture
(例如文件夹)内上传多张图片。
例如。 图片/a.jpg、图片/b.jpg、图片/c.jpg、.....
现在,我想直接将 Cloud Storage 中的多个图像作为列表显示到我的 cakephp 2.x Web 应用程序中。
根据 Google Cloud Storage 文档,要访问存储桶内的每个对象,Signed URLs必须生成。 因此,我根据从数据库中选择的数据为每个对象创建了签名 URL。以下是我的示例代码。
<?php
# Imports the Google Cloud client library
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Core\Exception\GoogleException;
function index() {
//$rsl = 'select data from database';
for($i=0; $i<$count; $i++) {
# create url to access image from google cloud storage
$file_path = $rsl[$i]['pic']['file_path'];
if(!empty($file_path)) {
$rsl[$i]['pic']['real_path'] = $this->get_object_v4_signed_url($file_path);
} else {
$rsl[$i]['pic']['real_path'] = '';
}
}
}
/**
* Generate a v4 signed URL for downloading an object.
*
* @param string $bucketName the name of your Google Cloud bucket.
* @param string $objectName the name of your Google Cloud object.
*
* @return void
*/
function get_object_v4_signed_url($objectName) {
$cloud = parent::connect_to_google_cloud_storage();
$storage = $cloud[0];
$bucketName = $cloud[1];
$bucket = $storage->bucket($bucketName);
$object = $bucket->object($objectName);
if($object->exists()) {
$url = $object->signedUrl(
# This URL is valid for 1 minutes
new \DateTime('1 min'),
[
'version' => 'v4'
]
);
} else {
$url = '';
}
return $url;
}
?>
问题是,生成时间太长,因为每个文件都是生成到 v4 签名的 URL。当我阅读 Google Cloud Storage 文档时,我没有看到同时生成多个对象的 v4 签名 URL(可能是我错了)。那么,有什么办法可以加快这个生成过程吗?
最佳答案
正如您提到的,Google Cloud Storage 文档中没有解释如何像您一样使用 PHP 为多个对象生成签名 URL。但是,我发现使用 gsutil signurl
命令,您可以指定多个路径,甚至可以使用通配符:
gsutil signurl -d 1m ~/sandbox/key.json gs://bucket_name/object_1.jpg gs://bucket_name/object_2.jpg ...
gsutil signurl -d 1m ~/sandbox/key.json gs://bucket_name/*
这在gsutil帮助signurl
页面中指定:“可以提供多个gs://url并且可以包含通配符。将为每个提供的url生成一个签名的url,并为指定的授权授权HTTP 方法并在给定的持续时间内有效。”
另一个选择可能是在您的应用程序中使用多线程,here您将了解如何使用 pthreads API 执行多线程处理。如果您选择使用此 API,您应该记住(来自 documentation):
Warning The pthreads extension cannot be used in a web server environment. Threading in PHP is therefore restricted to CLI-based applications only.
Warning pthreads (v3) can only be used with PHP 7.2+: This is due to ZTS mode being unsafe in 7.0 and 7.1.
但是既然你有一个网络应用程序,我认为这些解决方案对你来说都没有用。除此之外,您可以尝试使用 Cloud Functions生成签名 URL。
关于php - 我可以在 Google Cloud Storage 中同时为多个对象创建签名网址吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57368500/