您可以触发一个函数来响应上传、更新或删除云存储中的文件和文件夹。
此页面中的示例基于在图像文件上传到 Cloud Storage 时触发的示例函数。此示例函数演示了如何访问事件属性、如何将文件下载到 Cloud Functions 实例,以及处理 Cloud Storage 事件的其他基础知识。
有关用例的更多示例,请参阅我可以使用 Cloud Functions 做什么?
触发 Cloud Storage 更改的函数
使用functions.storage
创建一个处理 Cloud Storage 事件的函数。根据您是要将函数范围限定到特定 Cloud Storage 存储桶还是使用默认存储桶,请使用以下选项之一:
-
functions.storage.object()
用于侦听默认 Cloud Storage 存储桶上的对象更改。 -
functions.storage.bucket('bucketName').object()
用于侦听特定存储桶上的对象更改。
例如,缩略图生成器示例的范围限定为项目的默认存储桶:
exports.generateThumbnail = functions.storage.object().onFinalize(async (object) => { // ... });
Cloud Storage 支持这些事件:
-
onArchive
仅在存储桶启用对象版本控制时发送。此事件表示对象的实时版本已成为存档版本,因为它已存档或已被同名对象的上载覆盖。 -
onDelete
当对象被永久删除时发送。这包括作为存储桶生命周期配置的一部分被覆盖或删除的对象。对于启用了对象版本控制的存储桶,即使通过storage.objects.delete
方法进行归档,也不会在归档对象时发送(请参阅onArchive
)。 -
onFinalize
在桶中成功创建新对象(或现有对象的新一代)时发送。这包括复制或重写现有对象。上传失败不会触发此事件。 -
onMetadataUpdate
当现有对象的元数据更改时发送。
在on
事件处理程序中设置事件,如上所示的onFinalize
。
访问 Cloud Storage 对象属性
Cloud Functions 公开了许多 Cloud Storage 对象属性,例如更新文件的size
和contentType
。每当对象的元数据发生变化时, “元代”属性就会增加。对于新对象, metageneration
生成值为1
。
const fileBucket = object.bucket; // The Storage bucket that contains the file. const filePath = object.name; // File path in the bucket. const contentType = object.contentType; // File content type. const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.
缩略图生成示例使用其中一些属性来检测函数返回的退出情况:
// Exit if this is triggered on a file that is not an image. if (!contentType.startsWith('image/')) { return functions.logger.log('This is not an image.'); } // Get the file name. const fileName = path.basename(filePath); // Exit if the image is already a thumbnail. if (fileName.startsWith('thumb_')) { return functions.logger.log('Already a Thumbnail.'); }
下载、转换和上传文件
在某些情况下,可能不需要从 Cloud Storage 下载文件。但是,要执行密集型任务(例如从存储在 Cloud Storage 中的文件生成缩略图),您需要将文件下载到函数实例,即运行代码的虚拟机。
要轻松地将对象下载并重新上传到 Cloud Storage,请使用npm install --save @google-cloud/storage
安装Google Cloud Storage 包,然后将其导入。要使用 JavaScript promise 来处理外部进程,例如示例中的缩略图处理任务,还需要导入child-process-promise
:
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp() const spawn = require('child-process-promise').spawn; const path = require('path'); const os = require('os'); const fs = require('fs');
使用gcs.bucket.file(filePath).download
将文件下载到 Cloud Functions 实例上的临时目录。在此位置,您可以根据需要处理文件,然后上传到 Cloud Storage。执行异步任务时,确保在回调中返回 JavaScript promise。
示例:图像变换
Cloud Functions 提供了一个名为ImageMagick
的图像处理程序,可以对图形图像文件执行操作。以下是如何为上传的图像文件创建缩略图的示例:
// Download file from bucket. const bucket = admin.storage().bucket(fileBucket); const tempFilePath = path.join(os.tmpdir(), fileName); const metadata = { contentType: contentType, }; await bucket.file(filePath).download({destination: tempFilePath}); functions.logger.log('Image downloaded locally to', tempFilePath); // Generate a thumbnail using ImageMagick. await spawn('convert', [tempFilePath, '-thumbnail', '200x200>', tempFilePath]); functions.logger.log('Thumbnail created at', tempFilePath); // We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail. const thumbFileName = `thumb_${fileName}`; const thumbFilePath = path.join(path.dirname(filePath), thumbFileName); // Uploading the thumbnail. await bucket.upload(tempFilePath, { destination: thumbFilePath, metadata: metadata, }); // Once the thumbnail has been uploaded delete the local file to free up disk space. return fs.unlinkSync(tempFilePath);
此代码执行ImageMagick
命令行程序convert
为保存在临时目录中的图像创建 200x200 缩略图,然后将其上传回 Cloud Storage。
探索更多示例
常见媒体转换功能的更多示例,包括转码图像、调节内容、提取 EXIF 元数据。 GitHub 上提供了完整的示例列表。
有关详细信息,请参阅完整的 Google Cloud Storage 触发器文档。