问题描述
我在 API 中使用 google/cloud-storage
包并成功将 pdf 文件上传到 Google Cloud Storage 存储桶。但是,pdf 文件在上传到 Google Cloud Storage 存储分区之前首先保存在本地。
如何跳过将它们保存在本地,而是将它们直接上传到 Google Cloud Storage 存储桶?我计划在 Google App Engine 上托管 API。 这是它的 post。
这就是我目前正在做的:
$filename = $request['firstname'] . '.pdf';
$fileStoragePath = '/storage/pdf/' . $filename;
$publicPath = public_path($fileStoragePath);
$pdf = App::make('dompdf.wrapper');
$pdf->loadView('pdfdocument',$validatedData)
$pdf->save($publicPath);
$googleConfigFile = file_get_contents(config_path('googlecloud.json'));
$storage = new StorageClient([
'keyFile' => json_decode($googleConfigFile,true)
]);
$storageBucketName = config('googlecloud.storage_bucket');
$bucket = $storage->bucket($storageBucketName);
$fileSource = fopen($publicPath,'r');
$newFolderName = $request['firstname'].'_'.date("Y-m-d").'_'.date("H:i:s");
$googleCloudStoragePath = $newFolderName.'/'.$filename;
/*
* Upload a file to the bucket.
* Using Predefined ACLs to manage object permissions,you may
* upload a file and give read access to anyone with the URL.
*/
$bucket->upload($fileSource,[
'predefinedAcl' => 'publicRead','name' => $googleCloudStoragePath
]);
是否可以在不先将文件保存到本地的情况下将文件上传到 Google Cloud Storage 存储分区?
感谢您的帮助。
解决方法
我尚未验证此代码,但类 PDF 成员 output()
返回一个字符串。
$pdf = App::make('dompdf.wrapper');
$pdf->loadView('pdfdocument',$validatedData)
...
$bucket->upload($pdf->output(),[
'predefinedAcl' => 'publicRead','name' => $googleCloudStoragePath
]);
您可以简单地使用客户端代码。替换:
$googleConfigFile = file_get_contents(config_path('googlecloud.json'));
$storage = new StorageClient([
'keyFile' => json_decode($googleConfigFile,true)
]);
与
$storage = new StorageClient([
'keyFilePath' => config_path('googlecloud.json')
]);