tencent cloud

HarmonyOS Direct Upload Practice
Last updated: 2025-09-19 10:43:53
HarmonyOS 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 on the HarmonyOS system using simple code without relying on an SDK.
Notes:
Note: The content of this documentation is based on the XML version of the API.

Prerequisites

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

Practice Steps

Procedure:
1. The client calls the server API to input the file suffix. The server generates a cos key and a 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. After obtaining the information in procedure 3, the client directly initiates a put request and uploads with headers such as signature and token.
For specific code, see HarmonyOS sample code.

Configuring the Server to Implement Signatures

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 directly signs it. See Server Signature Practice.
Procedure:
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 = {
// Get Tencent Cloud Key, recommend using a Sub-user key with limited 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 extension limit
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, and the client process can begin.
For other languages or implementing your own, see the following process:
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 cos-sts-sdk.
2. Sign the direct upload url and generate authorization.
3. Return the direct upload url, authorization, sessionToken, etc. When uploading files, the client places the obtained signature and sessionToken in the authorization and x-cos-security-token fields of the request header.

HarmonyOS Upload Example

1. Request direct upload and signature information from the server.
import http from '@ohos.net.http';

/**
Get the direct upload url and signature
*
* @param ext File suffix. The backend generates a cos key based on the suffix for direct upload.
* @returns Direct upload url and signature
*/
public static async getStsDirectSign(ext: string): Promise<Object> {
// Each httpRequest corresponds to an HTTP request task and cannot be reused
let httpRequest = http.createHttp();
//Direct upload signature business server url (official environment, replace with official direct upload signature business url)
// For server-side code example of direct upload signature business, see: https://github.com/tencentyun/cos-demo/blob/main/server/direct-sign/nodejs/app.js
let url = "http://127.0.0.1:3000/sts-direct-sign?ext=" + ext;
try {
let httpResponse = await httpRequest.request(url, { method: http.RequestMethod.GET });
if (httpResponse.responseCode == 200) {
let result = JSON.parse(httpResponse.result.toString())
if (result.code == 0) {
return result.data;
} else {
console.info(`getStsDirectSign error code: ${result.code}, error message: ${result.message}`);
}
} else {
console.info("getStsDirectSign HTTP error code: " + httpResponse.responseCode);
}
} catch (err) {
console.info("getStsDirectSign Error sending GET request: " + JSON.stringify(err));
} finally {
// When the request is complete, call destroy to terminate.
httpRequest.destroy();
}
return null;
}
2. Use the obtained direct upload and signature information to start uploading files.
import http from '@ohos.net.http';
import promptAction from '@ohos.promptAction'
import fs from '@ohos.file.fs';
import request from '@ohos.request';
import common from '@ohos.app.ability.common';
import { MediaBean } from '../bean/MediaBean';
import { MediaHelper } from './MediaHelper';

/**
* Upload files (implemented via uploadTask)
* @param context context
* @param media Media file
*/
public static async uploadFileByTask(context: common.Context, media: MediaBean, progressCallback: (uploadedSize: number, totalSize: number) => void) {
// Get the direct upload signature and data
let ext = MediaHelper.getFileExtension(media.fileName);
let directTransferData: any = await UploadHelper.getStsDirectSign(ext);
if (directTransferData == null) {
promptAction.showToast({ message: 'getStsDirectSign fail' });
return;
}

// Upload information returned by the server
let cosHost: String = directTransferData.cosHost;
let cosKey: String = directTransferData.cosKey;
let authorization: String = directTransferData.authorization;
let securityToken: String = directTransferData.securityToken;

// Generate the uploaded url
let url = `https://${cosHost}/${cosKey}`;
try {
// Copy the uri file to cacheDir (because request.uploadFile only accepts internal: paths)
let file = await fs.open(media.fileUri, fs.OpenMode.READ_ONLY);
let destPath = context.cacheDir + "/" + media.fileName;
await fs.copyFile(file.fd, destPath);
let realuri = "internal://cache/" + destPath.split("cache/")[1];

let uploadConfig = {
url: url,
header: {
"Content-Type": "application/octet-stream",
"Authorization": authorization,
"x-cos-security-token": securityToken,
"Host": cosHost
},
method: "PUT",
files: [{ filename: media.fileName, name: "file", uri: realuri, type: ext }],
data: []
};
// Start uploading
let uploadTask = await request.uploadFile(context, uploadConfig)

uploadTask.on('progress', progressCallback);
let upCompleteCallback = (taskStates) => {
for (let i = 0; i < taskStates.length; i++) {
promptAction.showToast({ message: 'upload succeeded' });
console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i]));
}
};
uploadTask.on('complete', upCompleteCallback);

let upFailCallback = (taskStates) => {
for (let i = 0; i < taskStates.length; i++) {
promptAction.showToast({ message: 'upload failed' });
console.info("upOnFail taskState:" + JSON.stringify(taskStates[i]));
}
};
uploadTask.on('fail', upFailCallback);
} catch (err) {
console.info("uploadFile Error sending PUT request: " + JSON.stringify(err));
promptAction.showToast({ message: "uploadFile Error sending PUT request: " + JSON.stringify(err) });
}
}


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

Feedback