完成创建OSS触发器后,您可以开始编写函数代码。本文介绍如何使用函数计算控制台编写函数,实现OSS事件触发函数计算自定义处理OSS Bucket中的数据。

前提条件

创建触发器

操作步骤

  1. 登录函数计算控制台
  2. 在顶部菜单栏,选择地域。
  3. 在左侧导航栏,单击服务/函数
  4. 找到目标服务下的目标函数,单击函数名称。
  5. 单击代码执行页签,在代码编辑器中编写代码。

    代码示例如下。

     'use strict';
     console.log('Loading function ...');
     var oss = require('ali-oss').Wrapper;
     var fs = require('fs');
     var jimp = require("jimp");
     module.exports.resize = function (eventBuf, ctx, callback) {
         console.log('Received event:', eventBuf.toString());
         var event = JSON.parse(eventBuf);
         var ossEvent = event.events[0];
         // Required by OSS sdk: OSS region is prefixed with "oss-", e.g. "oss-cn-shanghai"
         var ossRegion = "oss-" + ossEvent.region;
         // Create oss client.
         var client = new oss({
             region: ossRegion,
             // Credentials can be retrieved from context
             accessKeyId: ctx.credentials.accessKeyId,
             accessKeySecret: ctx.credentials.accessKeySecret,
             stsToken: ctx.credentials.securityToken
         });
         // Bucket name is from OSS event
         client.useBucket(ossEvent.oss.bucket.name);
         // Processed images will be saved to processed/
         var newKey = ossEvent.oss.object.key.replace("source/", "processed/");
         var tmpFile = "/tmp/processed.png";
         // Get object
         console.log('Getting object: ', ossEvent.oss.object.key)
         client.get(ossEvent.oss.object.key).then(function (val) {
             // Read object from buffer
             jimp.read(val.content, function (err, image) {
                 if (err) {
                     console.error("Failed to read image");
                     callback(err);
                     return;
                 }
                 // Resize the image and save it to a tmp file
                 image.resize(128, 128).write(tmpFile, function (err) {
                     if (err) {
                         console.error("Failed to write image locally");
                         callback(err);
                         return;
                     }
                     // Putting object back to OSS with the new key
                     console.log('Putting object: ', newKey);
                     client.put(newKey, tmpFile).then(function (val) {
                         console.log('Put object:', val);
                         callback(null, val);
                         return;
                     }).catch(function (err) {
                         console.error('Failed to put object: %j', err);
                         callback(err);
                         return
                     });
                 });
             });
         }).catch(function (err) {
             console.error('Failed to get object: %j', err);
             callback(err);
             return
         });
     }; 
     # -*- coding: utf-8 -*-
     import oss2, json
     from wand.image import Image
     def resize(event, context):
         evt = json.loads(event)
         creds = context.credentials
         # Required by OSS sdk
         auth=oss2.StsAuth(
             creds.access_key_id,
             creds.access_key_secret,
             creds.security_token)
         evt = evt['events'][0]
         bucket_name = evt['oss']['bucket']['name']
         endpoint = 'oss-' +  evt['region'] + '.aliyuncs.com'
         bucket = oss2.Bucket(auth, endpoint, bucket_name)
         objectName = evt['oss']['object']['key']
         # Processed images will be saved to processed/
         newKey = objectName.replace("source/", "processed/")
         remote_stream = bucket.get_object(objectName)
         if not remote_stream:
             return
         remote_stream = remote_stream.read()
         with Image(blob=remote_stream)  as img:
             with img.clone() as i:
                 i.resize(128, 128)
                 new_blob = i.make_blob()
                 bucket.put_object(newKey, new_blob) 
    <?php
      use OSS\OssClient;
      function resize($event, $context) {
          $event           = json_decode($event, $assoc = true);
          $accessKeyId     = $context["credentials"]["accessKeyId"];
          $accessKeySecret = $context["credentials"]["accessKeySecret"];
          $securityToken   = $context["credentials"]["securityToken"];
          $evt        = $event['events'][0];
          $bucketName = $evt['oss']['bucket']['name'];
          $endpoint   = 'oss-' . $evt['region'] . '.aliyuncs.com';
          $objectName = $evt['oss']['object']['key'];
          $newKey = str_replace("source/", "processed/", $objectName);
          try {
              $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);
              $content = $ossClient->getObject($bucketName , $objectName);
              if ($content == null || $content == "") {
                 return;
              }
             $imagick = new Imagick();
             $imagick->readImageBlob($content);
             $imagick->resizeImage(128, 128, Imagick::FILTER_LANCZOS, 1);
             $ossClient->putObject($bucketName, $newKey, $imagick->getImageBlob());
         } catch (OssException $e) {
             print($e->getMessage());
         }
     } 

event格式说明

event是函数计算的入口参数,在指定的OSS Bucket发生对象创建或对象删除事件时,会将事件数据以JSON格式发送给绑定的函数。具体格式如下所示。

{
  "events": [
    {
      "eventName": "ObjectCreated:PutObject",
      "eventSource": "acs:oss",
      "eventTime": "2017-04-21T12:46:37.000Z",
      "eventVersion": "1.0",
      "oss": {
        "bucket": {
          "arn": "acs:oss:cn-shanghai:123456789:bucketname",
          "name": "testbucket",
          "ownerIdentity": "123456789",
          "virtualBucket": ""
        },
        "object": {
          "deltaSize": 122539,
          "eTag": "688A7BF4F233DC9C88A80BF985AB7329",
          "key": "image/a.jpg",
          "size": 122539
        },
        "ossSchemaVersion": "1.0",
        "ruleId": "9adac8e253828f4f7c0466d941fa3db81161e853"
      },
      "region": "cn-shanghai",
      "requestParameters": {
        "sourceIPAddress": "140.205.128.221"
      },
      "responseElements": {
        "requestId": "58F9FF2D3DF792092E12044C"
      },
      "userIdentity": {
        "principalId": "123456789"
      }
    }
  ]
}           

后续步骤

测试函数