雲存儲觸發器


您可以觸發函數來回應 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 公開許多 Clo​​s Storage 物件屬性,例如更新檔案的sizecontentType 。只要物件的元資料發生更改, “元生成”屬性就會增加。對於新對象,元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,請使用npm install --save @google-cloud/storage安裝Google Cloud Storage 軟體包,然後將其匯入。若要使用 JavaScript Promise 處理外部進程(例如範例中的縮圖處理任務),也需匯入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 實例上的臨時目錄。在此位置,您可以根據需要處理文件,然後上傳到雲端儲存。執行非同步任務時,請確保在回呼中傳回 JavaScript Promise。

範例:影像變換

將 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 上找到。