Firebase is back at Google I/O on May 10! Register now

雲存儲觸發器

透過集合功能整理內容 你可以依據偏好儲存及分類內容。

您可以觸發一個函數來響應上傳、更新或刪除雲存儲中的文件和文件夾。

此頁面中的示例基於在圖像文件上傳到 Cloud Storage 時觸發的示例函數。此示例函數演示瞭如何訪問事件屬性、如何將文件下載到 Cloud Functions 實例,以及處理 Cloud Storage 事件的其他基礎知識。

有關用例的更多示例,請參閱我可以使用 Cloud Functions 做什麼?

觸發 Cloud Storage 更改的函數

使用functions.storage創建一個處理 Cloud Storage 事件的函數。根據您是要將函數範圍限定到特定 Cloud Storage 存儲桶還是使用默認存儲桶,請使用以下選項之一:

例如,縮略圖生成器示例的範圍限定為項目的默認存儲桶:

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

Cloud Storage 支持這些事件:

  • onArchive僅在存儲桶啟用對象版本控制時發送。此事件表示對象的實時版本已成為存檔版本,因為它已存檔或已被同名對象的上載覆蓋。
  • onDelete當對像被永久刪除時發送。這包括作為存儲桶生命週期配置的一部分被覆蓋或刪除的對象。對於啟用了對象版本控制的存儲桶,即使通過storage.objects.delete方法進行歸檔,也不會在歸檔對象時發送(請參閱onArchive )。
  • onFinalize在桶中成功創建新對象(或現有對象的新一代)時發送。這包括複製或重寫現有對象。上傳失敗不會觸發此事件。
  • onMetadataUpdate當現有對象的元數據更改時發送。

on事件處理程序中設置事件,如上所示的onFinalize

訪問 Cloud Storage 對象屬性

Cloud Functions 公開了許多 Clo​​ud 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.
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 觸發器文檔