You can trigger a Cloud Function in response to the uploading, updating, or deleting of files and folders in Cloud Storage.
Examples in this page are based on a sample function that triggers when image files are uploaded to Cloud Storage. This sample function demonstrates how to access event attributes, how to download a file to a Cloud Functions instance, and other fundamentals of handling Cloud Storage events.
For more examples of use cases, see What can I do with Functions?
Trigger a Cloud Function on Cloud Storage changes
to create a Cloud Function that handles
Cloud Storage events. Depending on whether you want to scope your
Cloud Function to a specific Cloud Storage bucket or use the default
bucket, use one of the following:
functions.storage.object()to listen for object changes on the default storage bucket.
functions.storage.bucket(‘bucketName’).object()to listen for object changes on a specific bucket.
For example, the thumbnail generator sample is scoped to the default bucket for the project:
Cloud Storage supports the
change event. This event is triggered
whenever an object within your GCS bucket changes; for example, when an object
is created, modified, or deleted. Set the
change event within the
handler as shown above.
resourceState and other event attributes
Cloud Functions exposes a number of event attributes such as a
resource for the change,
for the file updated. The
attribute for an event has the value
"exists" (for object creation and
"not_exists" (for object deletion and moves).
The thumbnail generation sample uses some of these attributes to detect exit cases in which the function returns, including deletion events:
Download, transform, and upload a file
For some cases, it may not be necessary to download files from Cloud Storage. However, to perform intensive tasks such as generating a thumbnail image from a file stored in Cloud Storage, you need to download files to the functions instance—that is, the virtual machine that runs your code.
To easily download and re-upload objects to Cloud Storage, install the
Google Cloud Storage
handle external processes like the thumbnail processing tasks in the sample,
gcs.bucket.file(filePath).download to download a file to a temporary
directory on your Cloud Functions instance. In this location, you can
process the file as needed and then upload to Cloud Storage. When
Cloud Functions callback.
Example: image transformation
Cloud Functions provides an image-processing program called
ImageMagick that can perform
manipulations on graphical image files. The following is an example of how to
create a thumbnail image for an uploaded image file:
This code executes the
ImageMagick command line program
convert to create a
200x200 thumbnail for the image saved in a temporary directory, then uploads it
back to Cloud Storage.
Explore more examples
See the full Google Cloud Storage trigger documentation for more information.