All Products
Search
Document Center

Object Storage Service:Add signatures on the client and upload data to OSS

Last Updated:Jan 22, 2024

You can add signatures on the client by using JavaScript and upload data to Object Storage Service (OSS). With this method, you can directly upload objects from the client to OSS, which simplifies the workflow and accelerates the upload. This topic describes how to add signatures on the client based on POST policies and upload data to OSS by using form upload.

Usage notes

  • After you use JavaScript to add signatures on the client, you can upload data to OSS. However, your AccessKey ID and AccessKey secret may be exposed because they are included in the JavaScript code. We recommend that you Obtain signature information from the server and upload data to OSS or Use temporary credentials provided by STS to access OSS.

  • The application server code provided in this topic supports protocols such as HTML 4, HTML 5, Flash, and Silverlight. Make sure that your browser supports these protocols. If the "Your browser does not support Flash, Silverlight, or HTML5!" message appears, you need to upgrade your browser.

Procedure

Quick deployment

You can use Resource Orchestration Service (ROS) to configure an Elastic Compute Service (ECS) instance and an OSS bucket, and deploy client source code on the ECS instance. To use ROS to add signatures on the client based on POST policies and upload data to OSS, perform the following steps:

  1. Deploy cloud resources with a few clicks.

    1. Go to the Create Stack wizard in the ROS console.

    2. In the Select Template step of the Create Stack wizard in the ROS console, enter a stack name and the name of an OSS bucket that you want to create. Specify the zone, instance type, system disk category, and password for the ECS instance that you want to purchase, and then click Create.

      On the Stack Information tab of the page that appears, the status of the stack is Creating.

    3. After the status of the stack becomes Created, click the Outputs tab to view the resources, such as the ECS instance and OSS bucket, that are deployed with a few clicks.

  2. Add signatures on the client and upload data to OSS.

    1. On the Outputs tab, copy the value of UploadPath and open it in your browser.

    2. On the Transfer Data from Web Client to OSS page, click Select File, select a file of a specific type, and then click Upload.

  3. Release test resources to avoid unnecessary costs.

    1. In the upper-right corner of the stack page, click Delete.

    2. In the Delete Stack dialog box, set Method to Delete the Stack to Release Resources and click OK.

Manual deployment

Step 1: Download the client code that runs on browsers

Plupload is used in this example to upload form data (PostObject) to OSS. You can run the sample code in JavaScript on WeChat or browsers of computers or mobile phones. You can select multiple objects and specify the directory to which the objects are uploaded. You can also specify whether the names of the objects that you want to upload are the same as the names of the local files that you uploaded or whether the names are randomly specified by OSS. You can view the upload progress in the progress bar.

  1. Download the browser client code package.

  2. Decompress the downloaded package.

Note

In this example, Plupload is used as the frontend plug-in. You can use a different plug-in based on your business requirements.

Step 2: Modify the configuration file

  1. Modify access configurations.

    Open the upload.js file and use one of the following methods to modify the access configurations:

    Use a RAM user

    // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
    accessid= 'yourAccessKeyId';
    accesskey= 'yourAccessKeySecret';
    // Specify the domain name of a bucket. Format: BucketName.Endpoint. Example: http://examplebucket.oss-cn-hangzhou.aliyuncs.com. 
    host= 'yourHost';
    
    .....
    new_multipart_params = {
            ....
            'OSSAccessKeyId': accessid, 
            ....
        };

    Use STS

    // Specify the temporary AccessKey pair obtained from Security Token Service (STS). The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
    accessid= 'yourAccessKeyId';
    accesskey= 'yourAccessKeySecret';
    // Specify the domain name of a bucket. Format: BucketName.Endpoint. Example: http://examplebucket.oss-cn-hangzhou.aliyuncs.com. 
    host = 'http://examplebucketbucket.oss-cn-hangzhou.aliyuncs.com';
    // Specify the Alibaba Cloud Resource Name (ARN) of the specified role. Example: acs:ram::137918634953****:role/test. 
    STS_ROLE = '';
    
    .....
    new_multipart_params = {
            ....
            'OSSAccessKeyId': STS.accessid, 
            // Specify the security token obtained from STS. 
            'x-oss-security-token':STSToken,
            ....
        };
  2. Modify the policyText configuration to change the validity period of objects (expiration) and the size limit of the objects that you want to upload (content-length-range).

    var policyText = {
        "expiration": "2023-12-01T12:00:00.000Z", // Specify the validity period of objects in the policy. The time must be in UTC. After the validity period ends, you cannot upload objects. 
        "conditions": [
        ["content-length-range", 0, 1048576000] // Specify the size limit for the object that you want to upload. Unit: bytes. In this example, the size limit is 1 GB. If the object that you want to upload exceeds the size limit, the object fails to be uploaded to OSS. If you do not specify a size limit, you can upload an object whose size is up to 5 GB. 
        ]
    }

    For more information, see Appendix: Policy.

Step 3: Configure CORS

When you use form upload to upload data from the client to OSS, a request that contains the Origin header is sent from the browser to OSS. OSS verifies whether a request that includes the Origin header is a cross-origin request. Therefore, you must configure cross-origin resource sharing (CORS) rules for the bucket to allow POST-based requests.

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the left-side navigation pane, choose Content Security > CORS.

  4. On the CORS page, click Create Rule and configure the parameters shown in the following figure.

    Important

    To ensure data security, we recommend that you specify the actual domain name from which you want OSS to allow requests in the Source field. For more information, see Configure CORS.

Step 4: Add signatures on the client and upload data to OSS

  1. Open the index.html file in the directory that stores the decompressed downloaded file.

  2. Click Select File to select one or more objects that you want to upload. Then, select naming conventions for the objects, and specify the directory in which you want to store the objects.

  3. Click Upload and wait until the upload is complete.

  4. After the upload is complete, log on to the OSS console to view the upload objects.

Core code analysis

OSS supports POST requests. You must add a signature to a POST request when you use Plupload to send the request.

Note

To ensure that the code runs as expected, we recommend that you put the OSSAccessKeyId parameter in front of the key, success_action_status, and other parameters.

Core code

function set_upload_param(up, filename, ret)
{
  g_object_name = g_dirname;
  if (filename != '') {
      suffix = get_suffix(filename)
      calculate_object_name(filename)
  }
  new_multipart_params = {
      'OSSAccessKeyId': accessid,
      'key' : g_object_name,
      'policy': policyBase64,
      'success_action_status': '200', // If you do not set success_action_status to 200, HTTP status code 204 is returned after you upload the object. 
      'signature': signature,
  };

  up.setOption({
      'url': host,
      'multipart_params': new_multipart_params
  });

  up.start();
}
 ....

Retain the original names of the uploaded objects

'key': g_object_name specifies the path of the uploaded objects. If you want to retain the original names of the uploaded objects, set this field to 'key': '${filename}'. Sample code:

new_multipart_params = {
  'OSSAccessKeyId': accessid,
  'key': '${filename}',
  'policy': policyBase64,
  'success_action_status': '200', // If you do not set success_action_status to 200, HTTP status code 204 is returned after you upload the object. 
  'signature': signature,
};

Upload objects to a specific directory without changing the object names

If you want to upload objects to a specific directory such as the abc directory without changing the object names, set 'key': g_object_name to 'key': 'filepath' + '${filename}''. Sample code:

new_multipart_params = {
  'OSSAccessKeyId': accessid,
  'key': 'abc/' + '${filename}',
  'policy': policyBase64,
  'success_action_status': '200', // If you do not set success_action_status to 200, HTTP status code 204 is returned after you upload the object. 
  'signature': signature,
};

Specify that the names of the uploaded objects are randomly specified by OSS

If you want OSS to randomly specify the names of the uploaded objects, call the following function:

function check_object_radio() {
    g_object_name_type = 'random_name';
}

Specify names for uploaded objects

If you want to specify names for uploaded objects, call the following function:

function check_object_radio() {
    g_object_name_type = 'local_name';
}

Specify the directory to which you want to upload the objects

You can upload objects to a specific directory. The following sample code provides an example on how to set the directory to abc/. The directory name must end with a forward slash (/).

function get_dirname() {
    g_dirname = "abc/"; 
}

FAQ

How do I specify the formats of the objects that I want to upload?

You can use Plupload filters to configure upload conditions, such as the types of images and the size limits for the objects that you want to upload. For more information, see Configure upload conditions.

How do I obtain the URL of an uploaded object?

You can obtain the URL of an uploaded object based on the domain name of the bucket that stores the object and the object path. For more information, see Share objects with signed URLs.

How do I obtain the MD5 hash of an uploaded object?

To obtain the MD5 hash of an uploaded object, open the developer tools of your browser and upload an object. After the object is uploaded, you can view the MD5 hash in the response header, as shown in the following figure.