上传Object
更新时间:2025-04-01
最简单的上传
基本流程
- 创建BosClient 类的实例。
- 调用BOSClient.putObject()方法,支持将二进制串上传Object.
- 上传成功后即返回ETag.
示例代码
let etag: string;
try {
etag = await bosClient.putObject(<bucketName>, <objectName>, <buf>);
logger.info(`put object success, etag:${etag}`);
} catch (bosResponse) {
logger.error(`errCode: ${bosResponse.error.code}`)
logger.error(`requestId: ${bosResponse.error.requestId}`)
logger.error(`errMessage: ${bosResponse.error.message}`)
logger.error(`statusCode: ${bosResponse.statusCode}`)
}
参数说明
参数 | 说明 |
---|---|
bucketName | 存储桶名称 |
objectName | object名称 |
buf | 二进制流,类型为ArrayBuffer |
设定Object的Http Header或者标签
BOS支持您在上传object时设定Http Header。
基本流程
- 设置BasicMeta类以及TagConf类的实例.
- 根据需要设置不同的Header以及标签.
- 将设定后的meta作为参数加入putObject()中。
示例代码
let args = new BasicMeta();
let userMeta = new TreeMap<string, string>();
userMeta.set("region", "bj");
userMeta.set("type", "test");
args.userMeta = userMeta; // 用户自定义的元数据,但所有的User Meta总大小不能超过2KB。
args.cacheControl = "private"; // 下载Object的Cache设置,常见的可取值为private、no-cache、max-age、must-revalidate
args.contentDisposition = "inline"; // 设置浏览器是否下载,可取值为inline、attachment; filename="download.txt"
args.storageClass = "COLD"; // 存储类型
args.expires = "300"; // 用于设置下载Object时的缓存失效时间,如果不做时间设置,BOS则会默认设置缓存失效时间为三天。
args.trafficLimit = 8192000; // 单链接限速,取值范围为819200 ~ 838860800,单位为bit/s,即100KB/s~100MB/s
let tagConf = new TagConf();
let tag1 = new Tag(); // 标签设置
tag1.tagKey = "a";
tag1.tagValue = "b";
let tag2 = new Tag();
tag1.tagKey = "c";
tag1.tagValue = "d";
tagConf.tags = [tag1, tag2];
try {
await bosClient.putObject(<bucketName>, <objectName>, <buf>, <args>, <tagConf>);
} catch (bosResponse) {
logger.error(`errCode: ${bosResponse.error.code}`)
logger.error(`requestId: ${bosResponse.error.requestId}`)
logger.error(`errMessage: ${bosResponse.error.message}`)
logger.error(`statusCode: ${bosResponse.statusCode}`)
}
Append方式上传Object
BOS支持AppendObject,即以追加写的方式上传文件,适用场景如日志追加及直播等实时视频文件上传。通过AppendObject操作创建的Object类型为Appendable Object,可以对该Object追加数据;而通过PutObject上传的Object是Normal Object,不可进行数据追加写。AppendObject大小限制为0~5GB。
示例代码
// 从文件中读取数据
// 第一次append
let appendObjectResult: AppendObjectResult;
try {
// 首次append
appendObjectResult = await bosClient.appendObject(<bucketName>, <objectName>, <buf>);
logger.info(`create append object success`);
let args = new AppendObjectArgs(); //下一次追加写的参数
for (let i = 0; i < 100; ++i) {
args.offset = appendObjectResult.nextAppendOffset as number; // 本次追加写的偏移量
try {
appendObjectResult = await bosClient.appendObject(<bucketName>, <objectName>, <buf>, <args>);
logger.info(`append object success, ${i} times`);
} catch (bosResponse) {
logger.error(`errCode: ${bosResponse.error.code}`)
logger.error(`requestId: ${bosResponse.error.requestId}`)
logger.error(`errMessage: ${bosResponse.error.message}`)
logger.error(`statusCode: ${bosResponse.statusCode}`)
}
}
} catch (bosResponse) {
logger.error(`errCode: ${bosResponse.error.code}`)
logger.error(`requestId: ${bosResponse.error.requestId}`)
logger.error(`errMessage: ${bosResponse.error.message}`)
logger.error(`statusCode: ${bosResponse.statusCode}`)
}
参数说明
参数 | 说明 |
---|---|
bucketName | 存储桶名称 |
objectName | object名称 |
buf | 二进制流,类型为ArrayBuffer |
args | 追加写的参数, AppendObjectArgs类的实例 |
完整代码
import fs from '@ohos.file.fs';
import TreeMap from '@ohos.util.TreeMap';
import { logger, Credential, BosClient, ClientOptions} from "bos"
import { BasicMeta, TagConf, Tag, AppendObjectResult, AppendObjectArgs } from "bos/src/main/ets/bos/api/DataType"
let credential = new Credential(AccessKeyID, SecretAccessKey, Token); //STS返回的临时AK/SK及Token
let clientOptions = new ClientOptions();
clientOptions.endpoint = "bj.bcebos.com"; //传入Bucket所在区域域名
let bosClient = new BosClient(credential, clientOptions); // 创建BosClient
let bucketName = "test-bucket-harmony";
let objectName = "test-put-object";
// 创建一个临时文件
let cacheDir = getContext().cacheDir;
let path = cacheDir + '/test.txt';
let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE | fs.OpenMode.TRUNC)
fs.writeSync(file.fd, "Hello BOS");
fs.fsyncSync(file.fd);
fs.closeSync(file.fd);
file = fs.openSync(path, fs.OpenMode.READ_ONLY); // 使用同步的方式打开文件
let stat = fs.lstatSync(path); //获取文件的信息
let buf = new ArrayBuffer(stat.size); //构造ArrayBuffer
fs.readSync(file.fd, buf); // 读取文件内容
fs.fsyncSync(file.fd);
fs.closeSync(file.fd);
let etag: string;
try {
etag = await bosClient.putObject(bucketName, objectName, buf); //上传object
logger.info(`put object success, etag:${etag}`); // 打印etag
} catch (bosResponse) {
logger.error(`errCode: ${bosResponse.error.code}`)
logger.error(`requestId: ${bosResponse.error.requestId}`)
logger.error(`errMessage: ${bosResponse.error.message}`)
logger.error(`statusCode: ${bosResponse.statusCode}`)
}
let args = new BasicMeta();
let userMeta = new TreeMap<string, string>();
userMeta.set("region", "bj");
userMeta.set("type", "test");
args.userMeta = userMeta; // 用户自定义的元数据,但所有的User Meta总大小不能超过2KB。
args.cacheControl = "private"; // 下载Object的Cache设置,常见的可取值为private、no-cache、max-age、must-revalidate
args.contentDisposition = "inline"; // 设置浏览器是否下载,可取值为inline、attachment; filename="download.txt"
args.storageClass = "COLD"; // 存储类型
args.expires = "300"; // 用于设置下载Object时的缓存失效时间,如果不做时间设置,BOS则会默认设置缓存失效时间为三天。
args.trafficLimit = 8192000; // 单链接限速,取值范围为819200 ~ 838860800,单位为bit/s,即100KB/s~100MB/s
let tagConf = new TagConf();
let tag1 = new Tag(); // 标签设置
tag1.tagKey = "a";
tag1.tagValue = "b";
let tag2 = new Tag();
tag1.tagKey = "c";
tag1.tagValue = "d";
tagConf.tags = [tag1, tag2];
try {
await bosClient.putObject(bucketName, objectName, buf, args, tagConf);
} catch (bosResponse) {
logger.error(`errCode: ${bosResponse.error.code}`)
logger.error(`requestId: ${bosResponse.error.requestId}`)
logger.error(`errMessage: ${bosResponse.error.message}`)
logger.error(`statusCode: ${bosResponse.statusCode}`)
}
// 追加写的方式上传object
let appendObjectResult: AppendObjectResult;
try {
// 首次append
appendObjectResult = await bosClient.appendObject(bucketName, objectName, buf);
logger.info(`create append object success`);
let args = new AppendObjectArgs(); //下一次追加写的参数
// 测试多次append
for (let i = 0; i < 100; ++i) {
args.offset = appendObjectResult.nextAppendOffset as number; // 本次追加写的偏移量
try {
appendObjectResult = await bosClient.appendObject(bucketName, objectName, buf, args);
logger.info(`append object success, ${i} times`);
} catch (bosResponse) {
logger.error(`errCode: ${bosResponse.error.code}`)
logger.error(`requestId: ${bosResponse.error.requestId}`)
logger.error(`errMessage: ${bosResponse.error.message}`)
logger.error(`statusCode: ${bosResponse.statusCode}`)
}
}
} catch (bosResponse) {
logger.error(`errCode: ${bosResponse.error.code}`)
logger.error(`requestId: ${bosResponse.error.requestId}`)
logger.error(`errMessage: ${bosResponse.error.message}`)
logger.error(`statusCode: ${bosResponse.statusCode}`)
}