在Google Cloud中创建所有内容之后,编写代码以将图像从我的服务器上传到谷歌云,但我收到了谷歌存储类错误
我的upload_gcs.php代码
require 'vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Core\Exception\GoogleException;
if (isset($_FILES) && $_FILES['file']['error']== 0) {
$allowed = array ('png', 'jpg', 'gif', 'jpeg');
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array(strtolower ($ext), $allowed)) {
echo 'The file is not an image.';
die;
}
$projectId = 'photo-upload-205311';
$storage = new StorageClient ([
'projectId' => $projectId,
'keyFilePath' => 'Photo Upload-3af18f61531c.json'
]);
$bucketName = 'photo-upload-205311.appspot.com';
$bucket = $storage->bucket($bucketName);
$uploader = $bucket-> getResumableUploader (
fopen ($_FILES['file']['tmp_name'], 'r'),[
'name' => 'images/load_image.png',
'predefinedAcl' => 'publicRead',
]);
try {
$uploader-> upload ();
echo 'File Uploaded';
} catch (GoogleException $ex) {
$resumeUri = $uploader->getResumeUri();
$object = $uploader->resume($resumeUri);
echo 'No File Uploaded';
}
}
else {
echo 'No File Uploaded';
}
我得到的错误在
之下> Warning: The use statement with non-compound name
> 'GoogleCloudStorageStorageClient' has no effect in upload_gcs.php on
> line 4
>
> Fatal error: Class 'StorageClient' not found in upload_gcs.php on line
> 16
我的流程是否正确,或者是否有其他方法可以将图片从我的服务器上传到Google云端存储。
答案 0 :(得分:0)
必须使用脚本的正确命名空间,否则无法解析。见下面的更正。
<?php
require 'vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Core\Exception\GoogleException;
class GCPStorage {
function __construct()
{
$projectId = '<your-project-id>';
$bucketName = '<your-bucket-name>';
$storage = new StorageClient([
'projectId' => $projectId,
'keyFilePath' => '<your-service-account-key-file>'
]);
$this->bucket = $storage->bucket($bucketName);
}
function uploadToBucket()
{
if(/your-precondition/) {
return 'No File Uploaded';
}
$uploadedFileLocation = $_FILES['file']['tmp_name'];
$uploader = $this->bucket->getResumableUploader(
fopen($uploadedFileLocation, 'r'),
['name' => 'images/file.txt', 'predefinedAcl' => 'publicRead']
);
try {
$object = $uploader->upload();
} catch(GoogleException $ex) {
$resumeUri = $uploader->getResumeUri();
try {
$object = $uploader->resume($resumeUri);
} catch(GoogleException $ex) {
return 'No File Uploaded';
}
} finally {
return 'File Uploaded';
}
}
}
$gcpStorage = new GCPStorage;
echo $gcpStorage->uploadToBucket();
一个小建议:通过在失败时提前返回来提前确认你的前提条件作为保护条款。