Cloud Storage 觸發條件


您可以依據上傳、更新或刪除 Cloud Storage 中的檔案和資料夾來觸發函式。

本頁範例是以在圖片檔上傳至 Cloud Storage 時觸發的範例函式為基礎。這個範例函式示範如何存取事件屬性、如何將檔案下載至 Cloud Functions 執行個體,以及處理 Cloud Storage 事件的其他基礎知識。

如需更多用途範例,請參閱「Cloud Functions 提供哪些功能?」一文。

在 Cloud Storage 變更時觸發函式

使用 functions.storage 建立處理 Cloud Storage 事件的函式。根據您要將函式範圍限定為特定 Cloud Storage 值區,還是使用預設值區,使用下列其中一項:

舉例來說,縮圖產生器範例的範圍僅限於專案的預設值區:

exports.firstGenGenerateThumbnail = functions.storage.object().onFinalize(async (object) => {
  // ...
});

Cloud Storage 支援以下事件:

  • onArchive 只有在值區已啟用物件版本管理時,才會傳送此訊息。這個事件表示物件的使用中版本已變為封存版本,原因是物件遭到封存或是因為擁有相同名稱的物件上傳而遭到覆寫。
  • onDelete在永久刪除物件時傳送。這包含值區生命週期設定其中覆寫或刪除的物件。如果值區已啟用物件版本管理,則在封存物件時,系統不會傳送事件 (請參閱 onArchive),即使透過 storage.objects.delete 方法進行封存也是如此。
  • onFinalize當在值區中成功建立新物件 (或現有物件的新版本) 時,會傳送這個事件。複製或重寫現有的物件也包含在內。上傳失敗不會觸發這個事件。
  • onMetadataUpdate 在現有物件的中繼資料變更時傳送。

on 事件處理常式中設定事件,如上述的 onFinalize 所示。

存取 Cloud Storage 物件屬性

Cloud Functions 會顯示許多 Cloud Storage 物件屬性,例如更新檔案的 sizecontentType。每當物件的中繼資料發生變更時,'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 找到完整範例清單