After you create an Object Storage Service (OSS) trigger, you can start to define a function. This topic describes how to define a function in the Function Compute console, so that OSS events can trigger the function to perform custom data processing in an OSS bucket.


Create a trigger


  1. Log on to the Function Compute console.
  2. In the top navigation bar, select a region.
  3. In the left-side navigation pane, click Services and Functions.
  4. In the Services pane, click the service that you require. On the Functions tab, click the name of the function that you require.
  5. Click the Code tab and write code in the code editor.

    The following section shows the sample code:

     '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 =[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
         // 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
   , function (err, image) {
                 if (err) {
                     console.error("Failed to read image");
                 // 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");
                     // 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);
                     }).catch(function (err) {
                         console.error('Failed to put object: %j', err);
         }).catch(function (err) {
             console.error('Failed to get object: %j', err);
    # -*- 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
        evt = evt['events'][0]
        bucket_name = evt['oss']['bucket']['name']
        endpoint = 'oss-' +  evt['region'] + ''
        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:
        remote_stream =
        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) 
      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'] . '';
          $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 == "") {
             $imagick = new Imagick();
             $imagick->resizeImage(128, 128, Imagick::FILTER_LANCZOS, 1);
             $ossClient->putObject($bucketName, $newKey, $imagick->getImageBlob());
         } catch (OssException $e) {

Event format

event is an input parameter in Function Compute. When an object is created or deleted in a specified OSS bucket, the event data will be sent to the bound function in JSON format. The following section shows the format:

  "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": ""
      "responseElements": {
        "requestId": "58F9FF2D3DF792092E12044C"
      "userIdentity": {
        "principalId": "123456789"

What to do next

Test a function