It’s very easy to use Google Cloud Storage for images in website. It really helps to reduce development server load. Also, we can add some headers for images like cache control, expiry etc. It is not costly as compare to other storage.
Here you can see step-by-step guide to add images in storage using “gsutil” tool and add that images url from storage to your website.
Google Cloud Storage allows user to add images using google api, gsutil tool etc. Here we are going to use gsutil tool to upload images.
“gsutil” tool is provided by Google Cloud SDK which is very easy and powerful tool to copy, move, delete images from local storage or from your computer to Google Cloud Storage Bucket.
Next, you need to enter “gsutil” command to upload your images on Google Cloud Storage Bucket from your local system. For example, see below command
./gsutil -m cp /var/www/html/crm/wp-content/uploads/2021/04/*.jpeg gs://marketplace/images/
Here -m option is very useful if your uploading multiple images; it uploads images simultaneously to bucket.
cp option copying images from local to bucket. Here our bucket name is “marketplace” you can replace it with your own bucket name and “images” is sub-folder / sub-bucket (optional) which gets created automatically in bucket, here we are copying all images at once by providing *.jpeg / *.jpg etc.
You can also provide name of the file a.jpeg, if you want to upload images starts with a- then you can use a-*.jpeg for images a-1.jpeg, a-2.jpeg etc. to upload only single / multiple images.
/var/www/html/crm/wp-content/uploads/2021/04/*.jpeg this is folder which contain jpeg images.
gs://marketplace/images/ this Google Cloud Storage Bucket url which contains name of bucket “marketplace” and sub-folder / sub-bucket “images” (optional).
Also, if you use above command multiple times it just updates / replaces uploaded images, it does not create copy of the images.
Now in order to use browser cache capability, set metadata to images using below command to cache control, expiry etc.
./gsutil -m setmeta -h “Cache-Control:public, max-age=31536000” gs://marketplace/images/*.jpeg
here we are setting cache control public to save this image in browser cache so our bucket will not access every time and images are served from cache itself.
max-age is use to represent how many days or time image will be saved in browser cache, here we have used 31536000 seconds which is equal to 1 year.
Now we need to use public bucket url to load image from Google Cloud Storage. For example,
https://storage.googleapis.com/marketplace/images/a.jpeg
marketplace – Bucket name
images – sub-folder / sub-bucket name which we used while uploading command.
a.jpg – filename
That’s it now your are ready to serve images from Google Cloud Storage Bucket. Replace your website images url with bucket images url. It really helps to reduce server load and it comes with very low cost.