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

Torch Object Storage

Copy page
Download PDF
Best Practices
Uploading data from web browsers to TOS
Copy page
Download PDF
Uploading data from web browsers to TOS
You can use the PostObject API to upload content directly from a web browser as an HTML form to TOS. The signature required for the upload can be obtained from the server.​
For more information, see PostObject and Pre-signed Post Form.​
Step 1: Create a CORS rule​
When data is uploaded from a web browser, 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 web browsers 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 for browser-based uploads.​
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: Configure the server side code​
You can calculate a signature using the following example code on the server side.​
​
import express from "express";​
import TosClient from "@volcengine/tos-sdk";​
const app = express();​
const PORT = process.env.PORT || 8000; // Request port number​
​
const getSignature = async (bucket: string,key: string) => {​
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".​
endpoint: "Provide your endpoint" // Enter your regional access domain. For example, if your bucket is in China (Beijing), replace "Provide your endpoint" with "tos-cn-beijing.volces.com"。​
});​
​
const res = await client.preSignedPostSignature({​
bucket, // Enter the name of your bucket,e.g., examplebucket。​
key,​
});​
return res;​
};​
​
​
app.get("/get_post_signature", async (req, res) => {​
try {​
const key = req.query.key as string; // Retrieve the key from request parameters​
const bucket = req.query.bucket as string; // Retrieve the bucket from request parameters​
const result = await getSignature(bucket, key);​
res.setHeader("Access-Control-Allow-Origin", "*"); // Allow cross-origin requests​
res.setHeader("Access-Control-Allow-Headers", "*"); // Allow headers in cross-origin requests​
res.setHeader("Access-Control-Allow-Methods", "*"); // Allow methods in cross-origin requests​
res.json(result); // Return the signature information​
} catch (error) {​
console.error("Error generating signature:", error);​
res.status(500).send("Error generating signature");​
}​
});​
​
​
app.listen(PORT, () => {​
console.log(`Server is running on http://127.0.0.1:${PORT}`); ​
});​
​
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 access domain for the bucket.​
tip​
For more information on endpoints, see Regions and endpoints.​
​
Step 3: Configure the client side code​
You can use the following example code to upload content to TOS on the client side.​
​
<!DOCTYPE html>​
<html lang="en">​
<head>​
<meta charset="UTF-8" />​
<meta name="viewport" content="width=device-width, initial-scale=1.0" />​
<title>upload a file to TOS</title>​
</head>​
<body>​
<div class="container">​
<form>​
<div>​
<label for="file" class="form-label">select a file:</label>​
<input type="file" id="file" name="file" required />​
</div>​
<button type="submit">upload</button>​
</form>​
</div>​
<script>​
const form = document.querySelector("form");​
const url = "http://127.0.0.1:8000/get_post_signature"​
const bucket = "example-bucket";​
// Enter the regional access domain. In this example, the region is cn-beijing.​
const endpoint = "tos-cn-beijing.volces.com"​
form.addEventListener("submit", async (event) => {​
event.preventDefault();​
const fileInput = document.getElementById("file");​
const file = fileInput.files[0];​
if (!file) {​
alert("select a file");​
return;​
}​
console.log(file);​
const key = file.name;​
fetch(​
`${url}?key=${key}&bucket=${bucket}`,​
{​
method: "GET",​
}​
)​
.then((response) => {​
return response.json();​
})​
.then((data) => {​
const bucketHost = `${bucket}.${endpoint}`;​
const url = `https://${bucketHost}/${encodeURI(key)}`;​
const formData = new FormData();​
formData.append("key", data.key);​
formData.append("policy", data.policy);​
formData.append('x-tos-algorithm', data['x-tos-algorithm']);​
formData.append('x-tos-credential', data['x-tos-credential']);​
formData.append('x-tos-date', data['x-tos-date']);​
formData.append('x-tos-signature', data['x-tos-signature']);​
formData.append("x-tos-security-token", data["x-tos-security-token"]);​
formData.append("file", file);​
return fetch(url, {​
method: "POST",​
body: formData,​
});​
})​
.then((response) => {​
if (response.ok) {​
console.log("successfully uploaded");​
alert("file uploaded");​
} else {​
console.log("Upload failed", response);​
alert("Upload failed, please try again later");​
}​
})​
.catch((error) => {​
console.error("An error occurred:", error);​
});​
});​
</script>​
</body>​
</html>​
​
Replace the following parameters in the sample code with the appropriate values for your situation.​
​
Parameter​
Description​
url​
Specifies the server side URL.​
bucket​
Specifies the bucket in which the object will be stored.​
endpoint​
Specifies the regional access domain for the bucket.​
tip​
For more information on endpoints, see Regions and endpoints.​
​
​
Last updated: 2026.10.09 14:48:32