您可以在上傳、更新或刪除 Cloud Storage 中的檔案和資料夾時觸發函式。
本頁的範例是以圖片檔上傳到 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.firstGenGenerateThumbnail = functions.storage.object().onFinalize(async (object) => { // ... });
Cloud Storage 支援以下事件:
onArchive
只會在值區已啟用物件版本管理時傳送事件。這個事件表示物件的使用中版本已變為封存版本,原因是物件遭到封存或是因為擁有相同名稱的物件上傳而遭到覆寫。onDelete
會在永久刪除物件時傳送。這包含值區生命週期設定其中覆寫或刪除的物件。如果值區已啟用物件版本管理功能,則在封存物件時,系統不會傳送這項訊息 (請參閱onArchive
),即使透過storage.objects.delete
方法進行封存也一樣。onFinalize
當在值區中成功建立新物件 (或現有物件的新版本) 時,會傳送這個事件。複製或重寫現有的物件也包含在內。上傳失敗不會觸發這個事件。onMetadataUpdate
在現有物件的中繼資料變更時傳送。
按照上述的 onFinalize
方法,在 on
事件處理常式中設定事件。
存取 Cloud Storage 物件屬性
Cloud Functions 會公開多個 Cloud Storage 物件屬性,例如 size
和 contentType
,以便更新檔案。每當物件的中繼資料變更,'metageneration' 屬性就會遞增。如果是新物件,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.
縮圖產生範例會使用下列部分屬性,偵測函式傳回的離開事件:
// 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 承諾處理外部程序 (例如範例中的縮圖處理工作),請同時匯入 child-process-promise
:
const functions = require('firebase-functions/v1'); const admin = require('firebase-admin'); admin.initializeApp() const path = require('path'); //library for resizing images const sharp = require('sharp');
使用 gcs.bucket.file(filePath).download
,將檔案下載到 Cloud Functions 執行個體的暫存目錄。在這個位置中,您可以視需要處理檔案,然後上傳至 Cloud Storage。執行非同步工作時,請務必在回呼中傳回 JavaScript 承諾。
範例:圖片轉換
只要搭配使用 Cloud Functions 和圖片處理程式 (例如 sharp
),就能對圖形圖片檔執行操作。以下範例說明如何為上傳的圖片檔建立縮圖圖片:
// Download file from bucket. const bucket = admin.storage().bucket(fileBucket); const metadata = { contentType: contentType, }; const downloadResponse = await bucket.file(filePath).download(); const imageBuffer = downloadResponse[0]; functions.logger.log("Image downloaded!"); // Generate a thumbnail using sharp. const thumbnailBuffer = await sharp(imageBuffer).resize({ width: 200, height: 200, withoutEnlargement: true, }).toBuffer(); functions.logger.log("Thumbnail created"); // Upload the thumbnail with a 'thumb_' prefix. const thumbFileName = `thumb_${fileName}`; const thumbFilePath = path.join(path.dirname(filePath), thumbFileName); await bucket.file(thumbFilePath).save(thumbnailBuffer, { metadata: metadata, }); return functions.logger.log("Thumbnail uploaded!");
此程式碼會為暫存目錄中的圖片建立 200x200 縮圖,然後將其上傳至 Cloud Storage。
探索更多示例
更多常見的媒體轉換函式範例,包括轉碼圖片、審核內容、擷取 EXIF 中繼資料。您可以在 GitHub 找到完整的範例清單。