您可以觸發一個函數來響應上傳、更新或刪除雲存儲中的文件和文件夾。
此頁面中的示例基於在圖像文件上傳到 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
當對像被永久刪除時發送。這包括作為存儲桶生命週期配置的一部分被覆蓋或刪除的對象。對於啟用了對象版本控制的存儲桶,即使通過storage.objects.delete
方法進行歸檔,也不會在歸檔對象時發送(請參閱onArchive
)。 -
onFinalize
在桶中成功創建新對象(或現有對象的新一代)時發送。這包括複製或重寫現有對象。上傳失敗不會觸發此事件。 -
onMetadataUpdate
當現有對象的元數據更改時發送。
在on
事件處理程序中設置事件,如上所示的onFinalize
。
訪問 Cloud Storage 對象屬性
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.
縮略圖生成示例使用其中一些屬性來檢測函數返回的退出情況:
// 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 path = require('path'); //library for resizing images const sharp = require('sharp');
使用gcs.bucket.file(filePath).download
將文件下載到 Cloud Functions 實例上的臨時目錄。在此位置,您可以根據需要處理文件,然後上傳到 Cloud Storage。執行異步任務時,確保在回調中返回 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 上提供了完整的示例列表。