您可以響應上載,更新或刪除Cloud Storage中的文件和文件夾而觸發功能。
此頁面中的示例基於一個示例函數,該函數在將圖像文件上傳到Cloud Storage時觸發。此樣本功能演示瞭如何訪問事件屬性,如何將文件下載到Cloud Functions實例以及其他處理Cloud Storage事件的基礎知識。
有關用例的更多示例,請參閱如何使用雲功能?
觸發有關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) => { // ... });
雲存儲支持以下事件:
-
onArchive
僅在存儲桶啟用對象版本控制時發送。此事件表明某個對象的實時版本已成為歸檔版本,這是因為該對像已被歸檔,或者因為該對象的實時版本被上載相同名稱的對象所覆蓋。 -
onDelete
當對像已被永久刪除時發送。這包括作為存儲桶的生命週期配置的一部分而被覆蓋或刪除的對象。對於啟用了對象版本控制的存儲桶,即使歸檔是通過storage.objects.delete
方法進行的,也不會在歸檔對象時發送此消息(請參見onArchive
)。 -
onFinalize
在存儲桶中成功創建新對象(或現有對象的新一代)時發送。這包括複製或重寫現有對象。上載失敗不會觸發此事件。 -
onMetadataUpdate
當現有對象的元數據更改時發送。
在on
事件處理程序中設置事件,如上面onFinalize
所示。
訪問云存儲對象屬性
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中存儲的文件生成縮略圖,您需要將文件下載到function實例,即運行代碼的虛擬機。
要輕鬆地將對像下載並重新上傳到Cloud Storage,請使用npm install --save @google-cloud/storage
安裝Google Cloud Storage軟件包,然後將其導入。要使用JavaScript來處理示例中的縮略圖處理任務之類的外部流程,還需要導入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承諾。
示例:圖像轉換
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觸發器文檔。