This topic describes how to use JavaScript to add signatures on the client based on POST policies and then upload data to Object Storage Service (OSS) by using form upload.
Usage notes
- After you use JavaScript to add signatures on the client, you can directly 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 add signatures on the server to upload data. For more information, see Obtain signature information from the server and upload data to OSS or Use a temporary credential 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 a prompt such as "Your browser does not support Flash, Silverlight, or HTML5!" appears, upgrade your browser.
Step 1: Download the client code that runs on browsers
Plupload is used in this example to upload form data (PostObject) to OSS. The sample code in JavaScript can be run on WeChat or browsers from computers or mobile phones. You can select multiple objects for uploads and specify the destination directory. In addition, you can specify whether the names of the objects to upload are the same as the names of the local files that you upload or are randomly specified by OSS. You can view the upload progress by using the progress bar.
- Download the browser client code.
- Decompress the downloaded file.
Step 2: Modify the configuration file
Open the upload.js file and modify access configurations and use one of the following methods to modify:
Use a Resource Access Management (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 in the BucketName.Endpoint
format. Example: http://examplebucket.oss-cn-hangzhou.aliyuncs.com
.
host= 'yourHost';
.....
new_multipart_params = {
....
'OSSAccessKeyId': accessid,
....
};
Use Security Token Service (STS)
// Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret.
accessid= 'yourAccessKeyId';
accesskey= 'yourAccessKeySecret';
// Specify the domain name of a bucket in the BucketName.Endpoint
format. 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,
....
};
- For more information about the ARN of a role, see AssumeRole.
- For more information about how to obtain a temporary credential and security token from STS, see Use temporary credentials provided by STS to access OSS.
Step 3: Configure CORS
When you use form upload to upload data from the client to OSS, the client sends a request that contains the Origin
header to OSS by using the browser. 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 destination bucket to allow POST-based requests.
- Log on to the OSS console.
- In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
- In the left-side navigation tree, choose .
- Click Create Rule and configure the parameters as shown in the following figure. Note To ensure data security, we recommend that you specify the actual domain name from which you want OSS to allow requests in Sources. For more information about CORS configurations, see Configure CORS.
Step 4: Use JavaScript to add signatures on the client and upload data to OSS
- Open the index.html file in the directory that stores the decompressed downloaded file.
- Click Select File. Select one or more files to upload. Then, select a naming convention for the object to upload, and specify the directory in which you want to store the objects.
- Click Upload. Wait until the uploads are complete.
- After the uploads are complete, you can log on to the OSS console to view the upload results.
Core code analysis
OSS supports POST requests. Therefore, you need to add a signature to a POST request when you use Plupload to send the request. The following code provides an example on the 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, 204 status code is returned after the object is uploaded.
'signature': signature,
};
up.setOption({
'url': host,
'multipart_params': new_multipart_params
});
up.start();
}
....
In the preceding code, 'key': g_object_name
indicates the path of the uploaded object. If you want to retain the original name of the uploaded object, set this field to 'key': '${filename}'
.
To upload objects to a specific directory such as the abc directory without changing the object names, change part of the preceding code to the following code:
new_multipart_params = {
'OSSAccessKeyId': accessid,
'key' : 'abc/' + '${filename}',
'policy': policyBase64,
'success_action_status' : '200', // Set success_action_status to 200 so that 200 is returned if the request is successful. By default, 204 is returned.
'signature': signature,
};
- Specify random names for the objects that you upload
To instruct the system to randomly specify the name of an uploaded object without changing its name extension, use the following code to modify the function in the preceding code:
function check_object_radio() { g_object_name_type = 'random_name'; }
- Specify that the names of uploaded objects remain unchanged
To retain the original names of the objects, use the following code to modify the function in the preceding code:
function check_object_radio() { g_object_name_type = 'local_name'; }
- Configure the directory to which the object is uploaded
You can upload objects to a specific directory. The following code provides an example on how to set the destination directory to abc/. The destination directory must end with a forward slash (/).
function get_dirname() { g_dirname = "abc/"; }
- Upload the signature
When you upload objects, you must sign policyText. Example:
var policyText = { "expiration": "setDurationSeconds", // Set a proper validity period for the policy in UTC. After the validity period ends, you cannot upload objects to OSS by using this policy. "conditions": [ ["content-length-range", 0, 1048576000] // By default, the size limit for the object to upload is 5 GB. You can specify the size limit for the object to upload. If the uploaded object exceeds the size limit, OSS reports an error. ] }
FAQ
- Q: How do I specify the format of an object to upload?
A: You can set conditions for objects to upload by using the filters attributes of Plupload. For example, you can set conditions on the type of images and the size of objects. For more information, see Overview.
- Q: How do I obtain the URL of an uploaded object?
A: You can obtain the URL of an uploaded object based on the endpoint of the destination bucket and the object path. For more information, see How do I obtain the URL of a single object or the URLs of multiple objects?.
- Q: How do I obtain the MD5 hash of an uploaded object?
A: Open the developer tools of your browser, and then upload an object. After the object is uploaded, you can view the MD5 hash in the response header.