tencent cloud

Cloud Object Storage

Release Notes and Announcements
Release Notes
Announcements
Product Introduction
Overview
Features
Use Cases
Strengths
Concepts
Regions and Access Endpoints
Specifications and Limits
Service Regions and Service Providers
Billing
Billing Overview
Billing Method
Billable Items
Free Tier
Billing Examples
Viewing and Downloading Bill
Payment Overdue
FAQs
Getting Started
Console
Getting Started with COSBrowser
User Guide
Creating Request
Bucket
Object
Data Management
Batch Operation
Global Acceleration
Monitoring and Alarms
Operations Center
Data Processing
Content Moderation
Smart Toolbox
Data Processing Workflow
Application Integration
User Tools
Tool Overview
Installation and Configuration of Environment
COSBrowser
COSCLI (Beta)
COSCMD
COS Migration
FTP Server
Hadoop
COSDistCp
HDFS TO COS
GooseFS-Lite
Online Tools
Diagnostic Tool
Use Cases
Overview
Access Control and Permission Management
Performance Optimization
Accessing COS with AWS S3 SDK
Data Disaster Recovery and Backup
Domain Name Management Practice
Image Processing
Audio/Video Practices
Workflow
Direct Data Upload
Content Moderation
Data Security
Data Verification
Big Data Practice
COS Cost Optimization Solutions
Using COS in the Third-party Applications
Migration Guide
Migrating Local Data to COS
Migrating Data from Third-Party Cloud Storage Service to COS
Migrating Data from URL to COS
Migrating Data Within COS
Migrating Data Between HDFS and COS
Data Lake Storage
Cloud Native Datalake Storage
Metadata Accelerator
GooseFS
Data Processing
Data Processing Overview
Image Processing
Media Processing
Content Moderation
File Processing Service
File Preview
Troubleshooting
Obtaining RequestId
Slow Upload over Public Network
403 Error for COS Access
Resource Access Error
POST Object Common Exceptions
API Documentation
Introduction
Common Request Headers
Common Response Headers
Error Codes
Request Signature
Action List
Service APIs
Bucket APIs
Object APIs
Batch Operation APIs
Data Processing APIs
Job and Workflow
Content Moderation APIs
Cloud Antivirus API
SDK Documentation
SDK Overview
Preparations
Android SDK
C SDK
C++ SDK
.NET(C#) SDK
Flutter SDK
Go SDK
iOS SDK
Java SDK
JavaScript SDK
Node.js SDK
PHP SDK
Python SDK
React Native SDK
Mini Program SDK
Error Codes
Harmony SDK
Endpoint SDK Quality Optimization
Security and Compliance
Data Disaster Recovery
Data Security
Cloud Access Management
FAQs
Popular Questions
General
Billing
Domain Name Compliance Issues
Bucket Configuration
Domain Names and CDN
Object Operations
Logging and Monitoring
Permission Management
Data Processing
Data Security
Pre-signed URL Issues
SDKs
Tools
APIs
Agreements
Service Level Agreement
Privacy Policy
Data Processing And Security Agreement
Contact Us
Glossary

HarmonyOS Direct Upload Practice

PDF
Modo Foco
Tamanho da Fonte
Última atualização: 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) });
}
}



Ajuda e Suporte

Esta página foi útil?

comentários