如何使用 Google Cloud Storage 将文档直接保存到存储桶中,而不是保存在本地并使用 phpdocx 推送到 GCS?
我目前在下面有这段代码,我将其保存在本地,但我想直接将其保存在 GCS 中。
$newDocx->searchAndReplace($docxFromPath, public_path() . '/storage/agreements/docx' . $fileName, 'Company Name', 'Apple', $options);
附注我正在使用 Laravel 10
首先,您应该使用以下 Composer 命令在 Laravel 上安装 GCS:
composer require superbalist/laravel-google-cloud-storage
然后您应该通过在 Google Cloud 项目中创建服务帐户并下载 JSON 密钥文件来创建 Google Cloud Storage 凭证。尝试将此文件安全地存储在您的 Laravel 应用程序中,最好是在公共文件夹之外。
之后,您应该使用如下代码通过编辑 config/filesystems.php 来配置 Laravel 文件系统
'disks' => [
//.
//.
//.
'gcs' => [
'driver' => 'gcs',
'project_id' => env('GCS_PROJECT_ID'),
'key_file' => env('GCS_KEY_FILE'), // path to the JSON key
'bucket' => env('GCS_BUCKET'),
'path_prefix' => env('GCS_PATH_PREFIX', null), // optional: prefix for all object paths
'storage_api_uri' => env('GCS_STORAGE_API_URI', null), // optional: public URL to serve direct file uploads
],
],
确保在您的
.env
文件中设置相关的环境变量。
最后,您可以在代码中像下面这样使用它:
use Storage;
// Create the new document with phpdocx
$newDocx->searchAndReplace($docxFromPath, 'temporary-file.docx', 'Company Name', 'Apple', $options);
// Read the file into a variable
$fileContent = file_get_contents('temporary-file.docx');
// Save it to Google Cloud Storage
Storage::disk('gcs')->put('agreements/docx/'.$fileName, $fileContent);
// Optionally, delete the local temporary file
unlink('temporary-file.docx');
在此方法中,文档首先保存到您机器中的本地临时文件中,然后读取该文件的内容并将其上传到Google Cloud Storage。最后,本地文件被删除。