【问题标题】:Laravel: how to upload pdf file directly to Google Cloud Storage bucket without first saving it locallyLaravel:如何将 pdf 文件直接上传到 Google Cloud Storage 存储桶而无需先保存在本地
【发布时间】:2021-04-21 22:55:59
【问题描述】:

我在 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 存储桶?

感谢您的帮助。

【问题讨论】:

标签: laravel google-cloud-storage laravel-8


【解决方案1】:

我没有验证这个代码,但是类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')
]);

【讨论】:

    猜你喜欢
    • 2018-12-18
    • 1970-01-01
    • 2018-11-17
    • 2017-11-29
    • 2020-10-10
    • 2019-01-10
    • 2018-06-18
    • 2013-11-29
    • 1970-01-01
    相关资源
    最近更新 更多