This topic describes how to obtain signature information from the server in various programming languages based on POST policies, configure upload callback, and then directly upload data to Object Storage Service (OSS) by using form upload.

Background information

When users upload data by using the solution described in Obtain signature information from the server and upload data to OSS, the application server must be informed of the upload and the names of the objects. If images are uploaded, the application server must be informed of the sizes of the images. To meet this requirement, OSS provides the upload callback solution.

Process

The following figure shows how upload callback works.流程图EN

If you want the application server to receive an upload callback request when a user uploads an object to OSS, you must configure a callback function so that OSS sends the upload callback request to the application server. This way, after the user uploads the object, the application server returns a response to the upload callback request to OSS. Then, OSS forwards the response to the user, which is the upload result.

Examples

For more information about how to obtain signature information from the server, configure upload callback, and then directly upload data to OSS in various programming languages, see the following topics:

Process analysis

The services of obtaining signature information from the server, configuring upload callback, and then directly uploading data to OSS are available in PHP, Java, Python, Go, and Ruby. Process details:

  1. A user sends a request for an upload policy and upload callback to the application server.
  2. The application server returns the upload policy and the code to configure upload callback to the user.

    The application server processes the GET request from the client based on the services of obtaining signature information from the server and directly transferring data. You can configure the corresponding code so that the application server returns a correct message to the client. The configuration documents for different programming languages provide clear instructions for your reference.

  3. The user sends an object upload request directly to OSS.
  4. OSS sends a callback request to the application server based on callback configurations.

    After the object is uploaded to OSS, OSS analyzes the upload callback configurations of the client, and sends the POST callback request to the application server.

  5. The application server returns a response to OSS.

    The application server verifies the identification information based on authorization in the message from OSS. If the verification is successful, the application server returns the following message in the JSON format to OSS:

    {
    "String value": "ok",
    "Key": "Status"
    }
  6. OSS forwards the response from the application server to the user.

Client source code analysis

To download the client source code, click aliyun-oss-appserver-js-master.zip.
Note Plupload is used for the client JavaScript code. Plupload is a simple, easy-to-use, and powerful file uploading tool with extensive features. It supports multiple upload methods, including uploads by using HTML, Flash, Silverlight, and HTML4. Plupload detects the current environment to select the most suitable upload method, and HTML5 is prioritized. For more information about Plupload, visit Plupload.

The following section provides code samples on how to use some key features.

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

    To instruct OSS to randomly specify the object name without changing the name extension, you can use the following code to modify the function:

    function check_object_radio() {
        g_object_name_type = 'random_name';
    }
  • Specify that the names of uploaded objects remain unchanged

    To retain the original object name, you can use the following code to modify the function:

    function check_object_radio() {
        g_object_name_type = 'local_name';
    }
  • Configure the directory to which the object is uploaded
    The directory to which the object is uploaded is specified by the server. You can upload objects only to a specified directory to implement data isolation. The following code provides an example on how to set the directory to abc/ in PHP. The directory must end with a forward slash (/).
    $dir ='abc/';
  • Set upload conditions

    You can use Plupload filters to set upload conditions, such as uploading only images, the size of objects you want to upload, or denying the repeat upload of an object.

    var uploader = new plupload.Uploader({
        ...
        filters: {
            mime_types : [ 
            // Specify that only images and ZIP objects can be uploaded. 
            { title : "Image files", extensions : "jpg,gif,png,bmp" },
            { title : "Zip files", extensions : "zip" }
            ], 
            // Specify that only objects smaller than 400 KB in size can be uploaded. 
            max_file_size : '400kb', 
            // Specify that the repeat upload of an object is denied. 
            prevent_duplicates : true 
        },
    • mime_types: specifies the extensions of the objects to upload.
    • max_file_size: specifies the maximum size of the objects to upload.
    • prevent_duplicates: specifies that an object cannot be uploaded repeatedly.
  • Query the names of uploaded objects

    You can use Pupload to call the FileUploaded event and obtain the name of an uploaded object.

    FileUploaded: function(up, file, info) {
                if (info.status == 200)
                {
                    document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = 'upload to oss success, object name:' + get_uploaded_object_name(file.name);
                }
                else
                {
                    document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
                }
        }

    You can use the get_uploaded_object_name(file.name) function to obtain the name of the object that is uploaded to OSS, in which file.name records the name of the object before the object is uploaded.

  • Upload the signature

    You can obtain the policyBase64, accessid, and signature variables from the server by using JavaScript. The following code is the core code:

    function get_signature()
    {
        // Determine whether the value of the expire parameter exceeds the current time. If the value is within three seconds after the current time, you can still obtain the signature. 
        now = timestamp = Date.parse(new Date()) / 1000; 
        if (expire < now + 3)
        {
            body = send_request()
            var obj = eval ("(" + body + ")");
            host = obj['host']
            policyBase64 = obj['policy']
            accessid = obj['accessid']
            signature = obj['signature']
            expire = parseInt(obj['expire'])
            callbackbody = obj['callback'] 
            key = obj['dir']
            return true;
        }
        return false;
    };

    The following section provides an analysis of the message returned by the server.

    Note The message does not have a specific format. However, the accessid, policy, and signature fields are required in the message.
    {"accessid":"6MKO******4AUk44",
    "host":"http://post-test.oss-cn-hangzhou.aliyuncs.com",
    "policy":"eyJleHBpcmF0aW9uIjoiMjAxNS0xMS0wNVQyMDoyMzoyM1oiLCJjxb25kaXRpb25zIjpbWyJjcb250ZW50LWxlbmd0aC1yYW5nZSIsMCwxMDQ4NTc2MDAwXSxbInN0YXJ0cy13aXRoIiwiJGtleSIsInVzZXItZGlyXC8iXV19",
    "signature":"I2u57FWjTKqX/AE6doIdyff151E=",
    "expire":1446726203,"dir":"user-dir/"}
    • accessid: specifies the AccessKey ID that the user requests.
    • host: specifies the domain name to which you want to send the upload request.
    • policy: specifies the form upload policy, which is a string encoded in Base64. For more information, see PostObject.
    • signature: specifies the signature string that is generated from the Policy.
    • expire: specifies the time when the upload policy expires. The value of this parameter is specified on the server. Before the expiration time, users can repeatedly use the policy to upload objects. Users do not need to obtain signatures from the server for each upload.
    Note To reduce the server load, you can obtain the signature each time when you initialize an OSSClient instance to upload an object. When you use the OSSClient instance to upload another object, compare the current time with the expiration time of the signature to verify whether the signature has expired. If the signature expires, you must request a new signature. If the signature does not expire, you can use the existing signature.

    Policy analysis:

    {"expiration":"2015-11-05T20:23:23Z",
    "conditions":[["content-length-range",0,1048576000],
    ["starts-with","$key","user-dir/"]]

    In the preceding example, the starts-with field is added to the policy to specify that the object name must start with user-dir. You can also customize this field. The reason for adding the starts-with field is that in most scenarios, each application corresponds to a bucket. To prevent data from being overwritten, objects uploaded to OSS by users can be assigned a specific prefix. However, the user can upload multiple objects when the policy is valid, and the user can modify the prefix of the object and upload the object to the directory of another user. To solve this issue, the prefix is specified by the application server. This way, even if the user obtains the policy, the user cannot upload the object to the directory of another user, which ensures data security.

  • Configure the URL of the application server

    In the upload.js file of the client source code package, the value of the serverUrl variable in the following snippet can be used to set the URL of the application server. After the URL of the application server is set, the client sends a GET request to serverUrl to obtain required information.

    // serverUrl specifies the URL of the application server used to obtain information such as the signature and policy. Replace the IP address and port number with your actual information. 
    serverUrl = 'http://88.88.88.88:8888'

FAQ

How do I upload multiple objects to OSS at a time?

No API operation is available for uploading multiple objects to OSS at a time. To upload multiple objects to OSS at a time, you can repeat the process of uploading a single object described in this topic.