You need to enable JavaScript to run this app.
Torch Object Storage

Torch Object Storage

Copy page
Download PDF
Best Practices
Uploading data from WeChat Mini Programs to TOS
Copy page
Download PDF
Uploading data from WeChat Mini Programs to TOS
This topic describes how to upload files directly to TOS from WeChat Mini Programs.​
Background information​
WeChat Mini Programs, which can be used without downloading, are attracting a growing number of developers and users. One common concern for developers is how to upload files from a WeChat Mini Program to TOS. You can create a pre-signed post form and use the PostObject API to upload files from a WeChat Mini Program to TOS as an HTML form. For more information, see PostObject and Pre-signed Post Form.​
Step 1: Create a CORS rule​
When data is uploaded from a WeChat Mini Program, a cross-origin request is sent to TOS. TOS then verifies permissions by checking the bucket’s cross-origin resource sharing (CORS) rules. To ensure that WeChat Mini Programs can transfer data to TOS correctly, you must set up CORS rules in TOS. For more information, see CORS rules.​
  1. Log in to the TOS console.​
  1. In the left navigation pane, click Buckets. In the Buckets list, click the bucket you want to manage.​
  1. In the left navigation pane, select Permissions > CORS rules.​
  1. On the CORS rules page, click Create rule.​
  1. On the Create CORS Rule page, configure the following parameters:​
  • ​​​
  • ​
    Parameter​
    Description​
    Origin​
    Enter the domain name of your WeChat Mini Program.​
    tip​
    You can use a wildcard (*) to allow all origins.​
    Operation methods​
    Select PUT, GET, POST, DELETE, and HEAD.​
    Allow-Headers​
    Enter a wildcard (*).​
    Expose-Headers​
    Enter ETag, x-tos-request-id, and x-tos-version-id. Multiple entries are permitted, with each entry separated by a carriage return.​
    Cache Max-Age​
    Use the default value.​
    ​
  1. Click Create.​
Step 2: Add your domain to the allowlist​
To upload files from a WeChat Mini Program, a domain name must be added to its allowlist. Configure the allowlist in your WeChat Mini Program settings to include your TOS bucket's domain. This will allow normal interaction between your Mini Program and your bucket.​
tip​
We recommend associating your bucket with your own domain name so that you can access the objects stored in TOS via your domain. For instructions, see Associating a custom domain.​
  1. Obtain the bucket domain.​
  1. Log in to the TOS console.​
  1. In the left navigation pane, click Buckets. In the Buckets list, click the bucket you want to manage.​
  1. In the left navigation pane, click Overview.​
  1. On the Overview page, navigate to the Access domain area. In the Bucket domain column, find the corresponding domain name for Public Network Access.​
  1. Configure the allowlist.​
  1. Log in to the WeChat Mini Program management console.​
  1. On the Mini Program page, locate the Server Domain Names section and click Start Configuration.​
  1. In the Configure Server Domain Names dialog, enter your bucket's domain name in the uploadFile Valid Domain and downloadFile Valid Domain fields.​
  1. Click Save and Submit.​
Step 3: Upload data to TOS​
This JavaScript SDK sample demonstrates how to generate a signature using the calculatePostSignature method for a TOS PostObject request. Then, it shows how to use the WeChat Mini Program's uploadFile API to upload the file. The example code is shown below.​
​
// Ensure SDK version is 2.6.10 or later​
import { TosClient } from '@volcengine/tos-sdk'​
async function wxUploadToTOS() {​
// Create client​
const client = new TosClient({​
accessKeyId: "Provide your access key", // Enter the access key ID obtained through STS​
accessKeySecret: "Provide your secret key", // Enter the secret access key obtained through STS​
stsToken: "Provide your session token", // Enter the session token obtained through STS​
region: "Provide your region", // Specify the region where the bucket is located. For example, if your bucket is in China (Beijing), replace "Provide your region" with "cn-beijing".​
});​
​
const res = await wx.chooseMessageFile({ count: 1 });​
const path = res.tempFiles[0].path;​
const bucket = 'test-bucket';​
const key = 'wx-miniprogram-test';​
​
// For data security, we recommend uploading files using signature authentication. Learn more in https://www.volcengine.com/docs/6349/113484.​
For more information on pre-signed post form, refer to Browser-based uploads using HTTP POST.​
const formData = await client.calculatePostSignature({​
bucket,​
key,​
expiresIn: 3600,​
// To add custom fields, add these lines in your code:​
//fields: {​
// 'key': 'value'​
// }​
})​
// Replace bucketHost with the corresponding bucket domain ${bucket}.tos-${region}.volces.com​
const bucketHost = `${bucket}.tos-cn-beijing.volces.com`;​
const url = `https://${bucketHost}/${encodeURI(key)}`​
const result = await wx.uploadFile({​
filePath: path,​
name: 'file', // This is a fixed value.​
url,​
formData,​
success: (res) => {​
if (res.statusCode === 204) {​
console.log('Successfully Uploaded');​
}​
},​
fail: err => {​
console.log(err);​
}​
})​
console.log(result, 'result');​
}​
​
Replace the following parameters in the sample code with the appropriate values for your situation.​
​
Parameter​
Description​
accessKeyId​
Specifies the access key ID obtained through Security Token Service (STS).​
tip​
You can use STS to generate temporary access credentials, including temporary keys. For instructions, see Accessing TOS with temporary credentials of Security Token Service.​
accessKeySecret​
Specifies the secret access key obtained through STS.​
stsToken​
Specifies the session token obtained through STS.​
region​
Specifies the region of the bucket to which you want to upload the object.​
endpoint​
Specifies the regional node for the bucket.​
tip​
For more information on endpoints, see Regions and endpoints.​
const bucket​
Specifies the name of the bucket.​
const key​
Specifies the name of the object to be uploaded.​
const url​
Specifies the URL for access in the format https://<bucket domain>/<encoded object name>.​
​
​
Last updated: 2025.11.18 14:49:32