现在我正在努力允许用户使用 Google 云存储将图像上传到我的网站。上传常规图像文件(例如 jpg、png、gif 和 webp)效果很好。但是,SVG 图像不起作用。它们上传正常,但是当我让 PHP 代码将 URL 作为图像源回显时,所有浏览器都只显示丢失的图像图标。但是,看起来好像图像正在代码检查器的网络选项卡中下载。不仅如此,将链接粘贴到其自己的选项卡中会导致文件下载。这让我认为服务器告诉浏览器下载文件而不是将其作为图像提供。这是我正在使用的代码:
include 'GDS/GDS.php';
//create datastore
$obj_store = new GDS\Store('HomeImages');
$bucket = CloudStorageTools::getDefaultGoogleStorageBucketName();
$root_path = 'gs://' . $bucket . '/' . $_SERVER["REQUEST_ID_HASH"] . '/';
$public_urls = [];
//loop through all files that are images
foreach($_FILES['images']['name'] as $idx => $name) {
if ($_FILES['images']['type'][$idx] === 'image/jpeg' || $_FILES['images']['type'][$idx] === 'image/png' || $_FILES['images']['type'][$idx] === 'image/gif' || $_FILES['images']['type'][$idx] === 'image/webp' || $_FILES['images']['type'][$idx] === 'image/svg+xml') {
//path where the file should be moved to
$original = $root_path . 'original/' . $name;
//move the file
move_uploaded_file($_FILES['images']['tmp_name'][$idx], $original);
//don't use the getImageServingUrl function on SVG files because they aren't really images
if($_FILES['images']['type'][$idx] === 'image/svg+xml')
$public_urls[] = [
'name' => $name,
'original' => CloudStorageTools::getPublicUrl($original, true),
'thumb' => CloudStorageTools::getPublicUrl($original, true),
'location' => $original
];
else
$public_urls[] = [
'name' => $name,
'original' => CloudStorageTools::getImageServingUrl($original, ['size' => 1263, 'secure_url' => true]),
'thumb' => CloudStorageTools::getImageServingUrl($original, ['size' => 150, 'secure_url' => true]),
'location' => $original
];
}
}
//store image location and name in the datastore
foreach($public_urls as $urls){
$image = new GDS\Entity();
$image->URL = $urls['original'];
$image->thumbURL = $urls['thumb'];
$image->name = $urls['name'];
$image->location = $urls['location'];
$obj_store->upsert($image);
}
//redirect back to the admin page
header('Location: /admin/homeimages');
刚刚遇到这个问题,我找到了解决方案。事实证明,存储桶中的每个文件都附加了元数据并存储为键值对。我们要查找的键是“Content-Type”,该值对于 SVG 并不总是正确的。该值必须是“image/svg+xml”。我不知道如何以编程方式设置它,但如果您只有几个对象,那么在存储桶的在线界面中文件的省略号菜单中很容易完成。
感谢您发布如何解决此问题的信息。 以编程方式执行此操作的方法已在 @ https://cloud.google.com/storage/docs/viewing-editing-metadata#command-line
进行了描述例如:
gcloud storage objects update --content-type 'image/svg+xml' gs://my-bucket/images/dir/my-image.svg