tencent cloud

Flutter Direct Upload Practice
Last updated: 2025-09-19 10:43:53
Flutter Direct Upload Practice
Last updated: 2025-09-19 10:43:53

Overview

This documentation introduction explains how to directly upload files to a Cloud Object Storage (COS) bucket in Flutter with simple code, independent of SDK.
Notes:
The content of this documentation is based on the XML version of the API.

Prerequisites

1. Log in to the COS console and create a Bucket to get the Bucket name and Region. For details, see the create a Bucket document.
2. Log in to the Cloud Access Management console and obtain your project's SecretId and SecretKey.

Practice Steps

Procedure logic:
1. The client calls the server API to input the file suffix. The server generates a cos key and direct upload url based on the suffix and timestamp.
2. The server obtains a temporary key using the STS SDK.
3. The server signs the direct upload url with the obtained temporary key pair and returns the url, signature, token, etc.
4. The client obtains the information in procedure 3, directly initiates a put request with headers carrying signature and token, then uploads.
For specific code, see Flutter example.

Server

Notes:
Add a layer of authority check on your website itself when the server is officially deployed.
For security reasons, the backend obtains the temporary key, generates a direct upload url, and signs it directly. See Server Signature Practice.
Specific steps are as follows:
1. Obtain a temporary key using the STS SDK.
2. Generate a cos key and direct upload url based on the extension.
3. Sign the direct upload url with the temporary key and return the direct upload url, signature, token, etc.
Server configuration procedure:
1. Configure the key, bucket and region.
var config = {
// Retrieve Tencent Cloud Key, recommend using a Sub-user key with limit permissions https://console.tencentcloud.com/cam/capi
secretId: process.env.COS_SECRET_ID,
secretKey: process.env.COS_SECRET_KEY,
// key validity period
durationSeconds: 1800,
// Fill in the bucket and region here, for example: test-1250000000, ap-guangzhou
bucket: process.env.PERSIST_BUCKET,
region: process.env.PERSIST_BUCKET_REGION,
// Upload suffix limitation
extWhiteList: ['jpg', 'jpeg', 'png', 'gif', 'bmp'],
};
2. Execute in the terminal
npm install
3. Start the service.
node app.js
The server has started successfully here. You can now start the client process.
If any other languages or implement your own, see below:
1. Get a temporary key from the server. The server first uses the fixed key SecretId and SecretKey to obtain a temporary key from the STS service, getting the temporary key tmpSecretId, tmpSecretKey, and sessionToken. For details, see temporary key generation and usage guide or the cos-sts-sdk document.
2. Sign the direct upload url to generate authorization.
3. Return the direct upload url, authorization, sessionToken, etc. When uploading a file from the client, place the obtained signature and sessionToken into the authorization and x-cos-security-token fields in the header at the time of request.

Client (Flutter)

For specific code, see Flutter example.

Using the Dio Network Library

1. Request direct upload and signature information from the server.
/// Get the direct upload url and signature
/// @param ext File suffix. The backend generates a cos key based on the suffix for direct upload.
/// @return Direct upload url and signature
static Future<Map<String, dynamic>> getStsDirectSign(String ext) async {
Dio dio = Dio();
//Direct upload signature business server url (official environment, replace with the official direct upload signature business url)
//See direct upload signature business server example code: https://github.com/tencentyun/cos-demo/blob/main/server/direct-sign/nodejs/app.js
//10.91.22.16 is the server address for direct upload signature business, such as the above node service, in short, it is the url to access the direct upload signature business server
Response response = await dio.get('http://10.91.22.16:3000/sts-direct-sign',
queryParameters: {'ext': ext});
if (response.statusCode == 200) {
if (kDebugMode) {
print(response.data);
}
if (response.data['code'] == 0) {
return response.data['data'];
} else {
throw Exception(
'getStsDirectSign error code: ${response.data['code']}, error message: ${response.data['message']}');
}
} else {
throw Exception(
'getStsDirectSign HTTP error code: ${response.statusCode}');
}
}
2. Start uploading files using the obtained direct upload and signature information
Upload file
/// @param filePath file path
/// @param progressCallback Progress callback
static Future<void> upload(String filePath, ProgressCallback progressCallback) async {
String ext = path.extension(filePath).substring(1);
Map<String, dynamic> directTransferData;
try {
directTransferData = await getStsDirectSign(ext);
} catch (err) {
if (kDebugMode) {
print(err);
}
throw Exception("getStsDirectSign fail");
}
String cosHost = directTransferData['cosHost'];
String cosKey = directTransferData['cosKey'];
String authorization = directTransferData['authorization'];
String securityToken = directTransferData['securityToken'];
String url = 'https://$cosHost/$cosKey';
File file = File(filePath);
Options options = Options(
method: 'PUT',
headers: {
'Content-Length': await file.length(),
'Content-Type': 'application/octet-stream',
'Authorization': authorization,
'x-cos-security-token': securityToken,
'Host': cosHost,
},
);
try {
Dio dio = Dio();
Response response = await dio.put(url,
data: file.openRead(),
options: options, onSendProgress: (int sent, int total) {
double progress = sent / total;
if (kDebugMode) {
print('Progress: ${progress.toStringAsFixed(2)}');
}
progressCallback(sent, total);
});
if (response.statusCode == 200) {
if (kDebugMode) {
print('upload succeeded');
}
} else {
throw Exception("Upload failed ${response.statusMessage}");
}
} catch (error) {
if (kDebugMode) {
print('Error: $error');
}
throw Exception("Upload failed ${error.toString()}");
}
}

Using Native Http Client Network Library

1. Request direct upload and signature information from the server.
/// Get the direct upload url and signature
/// @param ext File suffix. The backend generates a cos key based on the suffix for direct upload.
/// @return Direct upload url and signature
static Future<Map<String, dynamic>> _getStsDirectSign(String ext) async {
HttpClient httpClient = HttpClient();
//Direct upload signature business server url (official environment, replace with the official direct upload signature business url)
//See direct upload signature business server example code: https://github.com/tencentyun/cos-demo/blob/main/server/direct-sign/nodejs/app.js
//10.91.22.16 is the server address for direct upload signature business, such as the above node service, in short, it is the url to access the direct upload signature business server
HttpClientRequest request = await httpClient
.getUrl(Uri.parse("http://10.91.22.16:3000/sts-direct-sign?ext=$ext"));
HttpClientResponse response = await request.close();
String responseBody = await response.transform(utf8.decoder).join();
if (response.statusCode == 200) {
Map<String, dynamic> json = jsonDecode(responseBody);
if (kDebugMode) {
print(json);
}
httpClient.close();
if (json['code'] == 0) {
return json['data'];
} else {
throw Exception(
'getStsDirectSign error code: ${json['code']}, error message: ${json['message']}');
}
} else {
httpClient.close();
throw Exception(
'getStsDirectSign HTTP error code: ${response.statusCode}');
}
}
2. Start uploading files using the obtained direct upload and signature information
Upload file
/// @param filePath file path
/// @param progressCallback Progress callback
static Future<void> upload(String filePath, ProgressCallback progressCallback) async {
// Get the direct upload signature and information
String ext = path.extension(filePath).substring(1);
Map<String, dynamic> directTransferData;
try {
directTransferData = await _getStsDirectSign(ext);
} catch (err) {
if (kDebugMode) {
print(err);
}
throw Exception("getStsDirectSign fail");
}

String cosHost = directTransferData['cosHost'];
String cosKey = directTransferData['cosKey'];
String authorization = directTransferData['authorization'];
String securityToken = directTransferData['securityToken'];
String url = 'https://$cosHost/$cosKey';

File file = File(filePath);
int fileSize = await file.length();
HttpClient httpClient = HttpClient();
HttpClientRequest request = await httpClient.putUrl(Uri.parse(url));
request.headers.set('Content-Type', 'application/octet-stream');
request.headers.set('Content-Length', fileSize.toString());
request.headers.set('Authorization', authorization);
request.headers.set('x-cos-security-token', securityToken);
request.headers.set('Host', cosHost);
request.contentLength = fileSize;
Stream<List<int>> stream = file.openRead();
int bytesSent = 0;
stream.listen(
(List<int> chunk) {
bytesSent += chunk.length;
double progress = bytesSent / fileSize;
if (kDebugMode) {
print('Progress: ${progress.toStringAsFixed(2)}');
}
progressCallback(bytesSent, fileSize);
request.add(chunk);
},
onDone: () async {
HttpClientResponse response = await request.close();
if (response.statusCode == 200) {
if (kDebugMode) {
print('upload succeeded');
}
} else {
throw Exception("Upload failed $response");
}
},
onError: (error) {
if (kDebugMode) {
print('Error: $error');
}
throw Exception("Upload failed ${error.toString()}");
},
cancelOnError: true,
);
}

Documentation

If you need to call richer APIs, see Flutter SDK.

Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback