使用 Amazon S3 觸發器建立縮圖
環境
centos (注意,必須是Linux環境)
node12.x
安裝教程
curl -sL https://rpm.nodesource.com/setup_12.x | sudo bash -
yum install -y nodejs yum install -y nodejs
參考文件:https://blog.csdn.net/Z_Z_W_/article/details/104988833
教程
\1. 建立一個名為lambda-s3資料夾
\2. 建立index.js檔案,儲存該內容如下,由程式碼可以看出,桶都是我們手動建立的,並不是程式碼幫我們建的
// dependencies const AWS = require('aws-sdk'); const util = require('util'); const sharp = require('sharp'); // get reference to S3 client const s3 = new AWS.S3(); exports.handler = async (event, context, callback) => { // Read options from the event parameter. console.log("Reading options from event:\n", util.inspect(event, {depth: 5})); const srcBucket = event.Records[0].s3.bucket.name; // Object key may have spaces or unicode non-ASCII characters. const srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " ")); const dstBucket = srcBucket + "-resized"; const dstKey = "resized-" + srcKey; // Infer the image type from the file suffix. const typeMatch = srcKey.match(/\.([^.]*)$/); if (!typeMatch) { console.log("Could not determine the image type."); return; } // Check that the image type is supported const imageType = typeMatch[1].toLowerCase(); if (imageType != "jpg" && imageType != "png") { console.log(`Unsupported image type: ${imageType}`); return; } // Download the image from the S3 source bucket. try { const params = { Bucket: srcBucket, Key: srcKey }; var origimage = await s3.getObject(params).promise(); } catch (error) { console.log(error); return; } // set thumbnail width. Resize will set the height automatically to maintain aspect ratio. const width = 200; // Use the sharp module to resize the image and save in a buffer. try { var buffer = await sharp(origimage.Body).resize(width).toBuffer(); } catch (error) { console.log(error); return; } // Upload the thumbnail image to the destination bucket try { const destparams = { Bucket: dstBucket, Key: dstKey, Body: buffer, ContentType: "image" }; const putResult = await s3.putObject(destparams).promise(); } catch (error) { console.log(error); return; } console.log('Successfully resized ' + srcBucket + '/' + srcKey + ' and uploaded to ' + dstBucket + '/' + dstKey); };
\3. 使用非root使用者在lambda-s3目錄下安裝sharp包,npm run sharp。注意:安裝sharp包對版本嚴格限制
參考文件:https://sharp.pixelplumbing.com/install
安裝好之後如下結構
\4. 在lambda下面打包成zip,將該zip檔案download下來,命令sz,然後把這個zip檔案上傳至aws lambda服務的 lambda函式
zip -r function.zip . ,該壓縮檔案我會放在最下面,負責人只需要知道原理就行,如果遇到這個需求,將該壓縮檔案下載下來就行,免去以上所有步驟
\5. 首先我們需要在s3建立一個源公開桶名為 meross-userfiles-mobilehub-1868304105,然後建立一個縮圖桶 meross-userfiles-mobilehub-1868304105-resized。key的路徑:如果你的key,都以public開頭,那麼對應縮圖桶的key路徑是以resized-public開頭,詳細請看以上js程式碼
\6. 在按照https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/with-s3-tutorial.html 文件設定好許可權之後,我們往 源桶的對應路徑下面上傳一個jpg檔案,
7.檢視目標桶
我們發現目標桶的縮圖自動建立成功
壓縮檔案下載:
參考文件
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/with-s3-tutorial.html