【发布时间】:2021-06-19 13:03:49
【问题描述】:
我正在尝试将图像文件上传到 GCS 中的存储桶,仅在我的页面上插入了一个文件输入和一个按钮以进行一些测试,当我单击该按钮时,它什么也没做,没有错误,什么也没有。我在 Google Cloud Platform Compute Engine 中使用 Ubuntu VM。 实际上我不能用谷歌云存储客户端做任何事情,不能上传对象,列出对象,列出存储桶,我已经把它上传到我的网站但它不起作用,首先在 localhost 上尝试但它给了我这个错误: cURL 错误 60: SSL 证书问题:无法获取本地颁发者证书,这就是我将其上传到 GCP 上的 VM 的原因。
<?php
require_once __DIR__.'/vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
class googleStorage{
private $projectId;
private $storage;
public function __construct() {
//putenv("GOOGLE_APPLICATION_CREDENTIALS=/var/www/html/vendor/google/Cloud/credentials.json");
$this->projectId = 'my_project_id';
$this->storage = new StorageClient([
'projectId' => $this->projectId
]);
$this->storage->registerStreamWrapper();
}
function uploadObject($bucketName, $objectName, $source) {
$file = fopen($source, 'r');
$bucket = $this->storage->bucket($bucketName);
$object = $bucket->upload($file, [
'name' => $objectName
]);
printf('Uploaded %s to gs://%s/%s' . PHP_EOL, basename($source), $bucketName, $objectName);
}
public function listBuckets() {
$buckets = $this->storage->buckets();
foreach ($buckets as $bucket) {
echo $bucket->name() . PHP_EOL;
}
}
function listObjects($bucketName) {
$bucket = $this->storage->bucket($bucketName);
foreach ($bucket->objects() as $object) {
printf('Object: %s' . '<br>', $object->name());
}
}
function getImageUrl($bucketName, $objectName) {
return 'https://storage.cloud.google.com/'.$bucketName.'/'.$objectName;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap Select-->
<link rel="stylesheet" href="vendor/bootstrap-select/css/bootstrap-select.min.css">
<title>Document</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="foto" class="form-control">
<button type="submit" name="upload" class="form-control">Upload</button>
</form>
<?php
include "googleStorage.php";
$bucket = "my_bucket";
$storage = new googleStorage();
$storage->listBuckets();
$storage->listObjects($bucket);
$imageUrl = $storage->getImageUrl($bucket, 'stitch.jpg');
if(isset($_POST['upload'])){
$storage->uploadObject($bucket, $_FILES['foto']['name'], $_FILES['foto']['tmp_name']);
}
?>
</body>
</html>
【问题讨论】:
-
该错误并非源自 Cloud Storage 或 Google Cloud。检查此question 有 9 个答案您应该尝试。
-
我知道 localhost 上的问题并非源自 Google Cloud,但是,我将文件上传到 Google Compute Engine 上的 VM 并且无法上传文件,所以我的问题是我无法使用 PHP 将图片上传到 Google Cloud Storage,cURL 错误仅发生在本地主机上,但我想从我的网站上传文件,感谢您的回答 @JohnMichaelGelilio,但它不能解决我的问题
-
不,@SoniSol 它没有回答我的问题
-
@Erik 转到您的Compute Engine,单击您的 vm 实例,然后检查您的 Cloud API 访问范围。如果将其设置为默认值,请尝试将其设置为允许完全访问所有云 API,您的 vm 实例将有权访问所有云 API,包括云存储。注意,您不能编辑 Cloud API 访问范围,您必须先停止 vm。
标签: php google-cloud-storage google-compute-engine