Download CV

Uploading Files/Images to Google Cloud Storage Bucket

24 September 2023

Uploading Files/Images to Google Cloud Storage Bucket: A Comprehensive Guide

In today’s digital age, the need for storing and managing large volumes of data, including files and images, has become more critical than ever. Businesses and developers often require scalable, reliable, and cost-effective solutions for storing and serving these assets. Two leading cloud storage solutions, Google Cloud Storage (GCS) and Amazon Simple Storage Service (Amazon S3), offer robust options to meet these needs. In this blog, we will explore why you might want to use Google Cloud Storage or Amazon S3 and provide a step-by-step guide to implementing file/image uploads to a Google Cloud Storage bucket.

Why Use Google Cloud Storage or Amazon S3?

  • Scalability Both Google Cloud Storage and Amazon S3 are highly scalable, allowing you to store vast amounts of data. They automatically handle the scaling for you, so you don’t need to worry about running out of space.

  • Durability and Reliability GCS and Amazon S3 offer high durability and reliability. They replicate your data across multiple data centers and have built-in redundancy, ensuring data integrity.

  • Security Both platforms provide robust security features, including access control, encryption, and audit logging, to protect your data. You can control who can access your files and under what conditions.

  • Cost-effectiveness They offer flexible pricing models, with pay-as-you-go options, which can help you manage costs efficiently. You pay only for the storage and bandwidth you use.

  • Integration Google Cloud Storage and Amazon S3 integrate seamlessly with other cloud services and tools, making it easier to build scalable and feature-rich applications.

Now, let’s dive into the step-by-step process of uploading files/images to a Google Cloud Storage bucket.

Step-by-Step Guide to Uploading Files/Images to Google Cloud Storage

Prerequisites

Before you begin, make sure you have the following prerequisites in place:

Laravel installed on your local machine or server.

  • A Google Cloud Platform (GCP) account with a project and Google Cloud Storage bucket created.
  • Composer installed to manage Laravel packages.
  • The Google Cloud Storage PHP SDK.

Step 1: Install the Google Cloud Storage PHP SDK

Use Composer to install the Google Cloud Storage PHP SDK. Open your terminal and navigate to your Laravel project directory, then run:

composer require google/cloud-storage

This command will download and install the necessary SDK files.

Step 2: Set Up Google Cloud Credentials

To authenticate your Laravel application with GCS, you need to set up your Google Cloud credentials. Follow these steps:

Go to the GCP Console and navigate to “IAM & Admin” > “Service accounts.”

  • Create a new service account or use an existing one.
  • Generate a JSON key file for your service account and save it securely on your server.

Step 3: Configure Laravel Environment

In your Laravel project, open the .env file and add the following environment variables:

GOOGLE_CLOUD_PROJECT_ID=your-project-id
GOOGLE_CLOUD_CONFIG=your-key-file.json
GOOGLE_CLOUD_BUCKET=your-bucket-name

Replace your-project-id, your-key-file.json, and your-bucket-name with your actual GCP project ID, key file name, and bucket name.

Step 4: Create a Route and Controller

Create a route in routes/api.php that points to a controller method to handle the file upload:

Route::post('/upload', 'FileUploadController@upload');

Now, create a controller using Artisan:

php artisan make:controller FileUploadController

Step 5: Create a File Upload helper class

In the FileUploaderHelper casll, add the following code to handle the file upload:

<?php

namespace App\StorageHelper;

use Google\Cloud\Storage\StorageClient;


class GoogleCloudStorage {

    public static function uploadFile($request, $bucketFolder)
    {
            $googleConfigJson = env('GOOGLE_CLOUD_CONFIG');

            $storage = new StorageClient([
                'keyFile' => json_decode($googleConfigJson, true)
            ]);
            $storageBucketName = config('googlecloud.storage_bucket');
            $bucket = $storage->bucket($storageBucketName);

            $image_path = $request->getRealPath();
            $path = uniqid() .'-'.time().'.'.$request->extension();
            $fileSource = fopen($image_path, 'r');
            $googleCloudStoragePath = $bucketFolder . "/" . $path;
            $bucket->upload($fileSource, [
                'predefinedAcl' => 'publicRead',
                'name' => $googleCloudStoragePath
            ]);

            return $path;
    }

}

In the FileUploadController, add the following code to handle the file upload:


use Illuminate\Http\Request;
use Google\Cloud\Storage\StorageClient;

class FileUploadController extends Controller
{
    public function upload(Request $request)
    {
        if ($request->hasFile("file")){

            $path = GoogleCloudStorage::uploadFile($request->file('file'), "bucketfolder");


        }

        // Return a success message or perform further actions
        return 'File uploaded successfully!';
    }
}


This controller method uses the Google Cloud Storage PHP SDK to upload the file to your GCS bucket.

Step 5: Test the File Upload

Start your Laravel development server:

php artisan serve
Comments