Directly upload files from a Douyin mini program to OSS
You can directly upload content, such as images and videos, from a Douyin mini program to Object Storage Service (OSS). This method avoids forwarding content through your application server. Direct uploads to OSS reduce server load, increase upload speed, and improve user experience.
Prerequisites
-
The Douyin developer tools are installed. To download the tools, see Developer tools.
-
A bucket is created. For more information, see Create a bucket.
Preparations
When you directly upload files from a Douyin mini program to OSS, the client does not use a long-term AccessKey pair. To ensure the security of upload requests, a Resource Access Management (RAM) user assumes a RAM role to request a temporary access credential from Security Token Service (STS).
Procedure 1: Create a RAM user in Resource Access Management
First, create a RAM user and obtain its AccessKey pair. This pair serves as the long-term identity credential for your application server.
-
Log on to the RAM console using an Alibaba Cloud account or a RAM administrator.
-
In the navigation pane on the left, choose Identity Management > Users.
-
Click Create User.
-
Enter a Logon Name and a Display Name.
-
In the Access Mode section, select Programmatic Access, and then click OK.
The AccessKey secret of a RAM user is displayed only when the user is created and cannot be retrieved later. You must store it securely.
-
In the Actions column, click Copy to save the AccessKey ID and AccessKey secret.
Step 2: Grant the RAM user permissions to call the AssumeRole operation
After you create the RAM user, grant the user permissions to call the AssumeRole operation of STS. This allows the user to obtain a temporary identity credential by assuming a RAM role.
-
In the navigation pane on the left, choose Identity Management > Users.
-
On the Users page, find the target RAM user and click Add Permissions in the Actions column.
-
On the Add Permissions page, select the AliyunSTSAssumeRoleAccess system policy.
NoteThe AliyunSTSAssumeRoleAccess policy grants the RAM user fixed permissions to call the AssumeRole operation of STS. This policy is not related to the permissions required to obtain a temporary access credential or to initiate OSS requests using the temporary credential.
-
Click Confirm New Authorization.
Step 3: Create a RAM role in the RAM console
Create a RAM role for the current Alibaba Cloud account and obtain its ARN (Alibaba Cloud Resource Name). The RAM user will assume this role later.
-
In the navigation pane on the left, choose Identity Management > Roles.
-
Click Create Role. For Trusted Entity Type, select Alibaba Cloud Account.
-
Select Current Alibaba Cloud Account, and then click OK.
-
Enter a role name and click OK.
-
On the RAM role management page, click Copy to save the role's ARN.
Step 4: Create a permission policy for file uploads in the RAM console
Following the Principle of Least Privilege (PoLP), create a custom policy for the RAM role. This policy restricts upload operations to a specific OSS bucket.
-
In the navigation pane on the left, choose Permission Management > Policies.
-
Click Create Policy.
-
On the Create Policy page, click the Script tab. In the following script, replace
<BucketName>with the name of your bucket, for example,web-direct-upload.{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": "oss:PutObject", "Resource": "acs:oss:*:*:<BucketName>/*" } ] } -
After you configure the policy, click Continue to Edit Basic Information.
-
In the Basic Information section, enter a policy name and click OK.
Step 5: Grant permissions to the RAM role in the RAM console
Grant the custom policy to the RAM role. This ensures that the role has the required permissions when it is assumed.
-
In the navigation pane on the left, choose Identity Management > Roles.
-
On the Roles page, find the target RAM role and click Add Permissions in the Actions column.
-
On the Add Permissions page, select Custom Policy and select the custom policy that you created.
-
Click OK.
Deploy the solution
-
Modify the
getToken.jsconfiguration in the express-douyin.zip sample project.const crypto = require("crypto-js"); const STS = require("ali-oss").STS; const { accessKeyId, secretAccessKey: accessKeySecret } = process.env; const stsClient = new STS({ // Obtain the AccessKey pair of the RAM user that you created in the Preparations section from environment variables. Before you run this code sample, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. accessKeyId: process.env.OSS_ACCESS_KEY_ID, accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET, // Specify the bucket name. bucket: "examplebucket", }); async function getToken() { // Specify the ARN of the role that you created in the Preparations section. The format is acs:ram::$accountID:role/$roleName. const STS_ROLE = "acs:ram::137****:role/ramosstest"; const STSpolicy = { Version: "1", Statement: [ { Effect: "Allow", Action: "oss:PutObject", Resource: "acs:oss:*:*:examplebucket/*", }, ], }; const result = await stsClient.assumeRole( STS_ROLE, STSpolicy, 3600 // The validity period of the STS token, in seconds. ); const { credentials } = result; return credentials; } // Calculate the signature. function computeSignature(accessKeySecret, canonicalString) { return crypto.enc.Base64.stringify( crypto.HmacSHA1(canonicalString, accessKeySecret) ); } const date = new Date(); date.setHours(date.getHours() + 1); const policyText = { expiration: date.toISOString(), // Set the expiration time of the policy. conditions: [ // Limit the upload size. ["content-length-range", 0, 1024 * 1024 * 1024], ], }; module.exports.getToken = getToken; module.exports.policyText = policyText; module.exports.computeSignature = computeSignature; -
Obtain the client signature information.
-
Open the
express-app.jsfile and run thenode express-app.jscommand.const express = require("express"); const app = express(); const { Base64 } = require("js-base64"); const MpUploadOssHelper = require("./uploadOssHelper.js"); const { getToken, policyText, computeSignature } = require("./getToken"); // Obtain the client signature. app.get("/getFormDataParams", async (req, res) => { // Obtain the STS token. const { AccessKeySecret, AccessKeyId, SecurityToken } = await getToken(); const policy = Base64.encode(JSON.stringify(policyText)); // The policy must be a Base64-encoded string. const signature = computeSignature(AccessKeySecret, policy); const formData = { OSSAccessKeyId: AccessKeyId, signature, policy, SecurityToken, }; res.json(formData); }); app.listen(3001); -
In a browser, enter
http://localhost:3001/getFormDataParamsto obtain the signature information.{ "OSSAccessKeyId":"STS.NTm****", "signature":"nS3Z****", "policy":"eyJleH****", "SecurityToken":"CAIS****" }
-
-
Use the Douyin developer tools to directly upload a file to OSS.
-
Decompress the douyin-detail.zip project file.
-
Open the Douyin developer tools and import the decompressed project.
-
In the
page/tt-templates-articlepath, modify thehostconfiguration item in theindex.jsfile. You can keep the default configurations for the other options.const app = getApp(); const timeago = require("./timeago.js"); import { templateDataValidator } from "./validator"; // const STS = require("ali-oss").STS; // Specify the public endpoint of the bucket. const host = 'https://examplebucket.oss-cn-hangzhou.aliyuncs.com'; Page({ onLoad(options) { }, chooseImage: function() { var that = this; // Select an image. tt.chooseImage({ count: 1, // Specify the number of images. The default value is 9. sizeType: ['original', 'compressed'], // Specify whether to upload the original or compressed image. By default, both are allowed. sourceType: ['album', 'camera'], // Specify whether the source is an album or a camera. By default, both are allowed. success: function(res) { console.log('Original', res); // After an image is selected, obtain the local path of the image file. // var localIds = res.tempFiles; var localIds = res.tempFilePaths; // Use uploadFile to upload the image. that.uploadImage(localIds[0]); } }); }, uploadImage: function(path) { const signature = 'signatureString'; const ossAccessKeyId = 'accessKey'; const key = ''; const securityToken = 'x-oss-security-token'; // Obtain the token and other related information. tt.request({ url:'http://localhost:3001/getFormDataParams', success: function(res) { const {OSSAccessKeyId, policy, signature, SecurityToken} = res.data; console.log('SecurityToken', SecurityToken); // Upload the image. tt.uploadFile({ url: host, filePath: path, name: 'file', formData: { key: path.split('/').pop(), // Set the path of the file after it is uploaded to OSS. policy, OSSAccessKeyId, signature, // success_action_status: '200', // Pass the securityToken when you use an STS signature. 'x-oss-security-token': SecurityToken }, success: function(res) { // Information returned by the server after the upload is successful. var serverId = res.serverId; // The server ID is returned. console.log('Image uploaded successfully. Server ID:', res); // Send the serverId to the server for operations such as saving. }, fail: function(err) { console.log('Image upload failed:', err); } }); }, fail: function(err) { } }); } }); -
Select an image and upload it to OSS.
-