Laravel: how to upload pdf file directly to Google Cloud Storage bucket without first saving it locally

I am using the google/cloud-storage package in an API and successfully uploading pdf files to a Google Cloud Storage bucket. However, the pdf files are first saved locally before they are uploaded to the Google Cloud Storage bucket.

How can I skip saving them locally and instead upload them directly to the Google Cloud Storage bucket? I am planning to host the API on Google App Engine.
This is the post for it.

This is what I am doing currently:

$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
]);

Is it possible to upload files to a Google Cloud Storage bucket without first saving them locally?

Thank you for your help.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I have not verified this code, but the class PDF member output() returns a string.

$pdf = App::make('dompdf.wrapper');
$pdf->loadView('pdfdocument', $validatedData)

...

$bucket->upload($pdf->output(), [
    'predefinedAcl' => 'publicRead',
    'name' => $googleCloudStoragePath
]);

You can simply the client code. Replace:

$googleConfigFile = file_get_contents(config_path('googlecloud.json'));
$storage = new StorageClient([
    'keyFile' => json_decode($googleConfigFile, true)
]);

with

$storage = new StorageClient([
    'keyFilePath' => config_path('googlecloud.json')
]);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x