对象大于 5GiB 时,需要使用 uploadPartCopy 来进行分片拷贝。
以下代码展示如何通过 createMultipartUpload、uploadPartCopy 和 completeMultipartUpload 从 harmonyos-sdk-test-bucket 桶分片拷贝 source-test 对象到 harmonyos-sdk-copy-bucket 桶,并将拷贝的对象命名为 copy-test。
import { TosClient, TosClientError, TosServerError } from '@volcengine/tos_harmonyos_sdk'; // 创建客户端 const client = new TosClient({ accessKeyId: "Provide your ak", accessKeySecret: "Provide your sk", securityToken: 'Provide your securityToken', region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,"Provide your region" 填写为 cn-beijing。 endpoint: "Provide your endpoint", // 填写域名地址 }); function handleError(error) { if (error instanceof TosClientError) { console.log('Client Err Name:', error.name); console.log('Client Err Msg:', error.message); console.log('Client Err Stack:', error.stack); } else if (error instanceof TosServerError) { console.log('Request ID:', error.requestId); console.log('Response Status Code:', error.statusCode); console.log('Response Status Code:', error.statusCode); console.log('Response Header:', error.headers); console.log('Response Err Code:', error.code); console.log('Response Err Msg:', error.message); } else { console.log('unexpected exception, message: ', error); } } async function main() { try { const srcBucket = 'harmonyos-sdk-test-bucket'; // 源桶 const srcObject = 'source-test'; // 源对象 const dstBucket = 'harmonyos-sdk-copy-bucket'; // 目标桶 const dstObject = 'copy-test'; // 目标对象 let res = await client.createMultipartUpload({ Bucket: dstBucket, Key: dstObject, }) console.log('create part: ', res.UploadId) const res2 = await client.headObject({ Bucket: srcBucket, Key: srcObject, }) console.log('srcObject content-length', res2.ContentLength); const totalSize = res2.ContentLength; const partSize = 5 * 1024 * 1024; let offset = 0; let partNumber = 1; const partsInfo: UploadedPart[] = []; while (offset < totalSize) { // 上传分片拷贝 const uploadResult = await client.uploadPartCopy({ Bucket: dstBucket, Key: dstObject, PartNumber: partNumber, UploadID: res.UploadId, SrcBucket: srcBucket, SrcKey: srcObject, CopySourceRangeStart: offset, CopySourceRangeEnd: offset + partSize - 1, }); const eTag = uploadResult.ETag; console.log(`partNumber${partNumber} Etag:`, eTag); partsInfo.push(new UploadedPart(partNumber, eTag)); partNumber++; offset += partSize; } const res3 = await client.completeMultipartUpload({ Bucket: dstBucket, Key: dstObject, UploadID: res.UploadId, Parts: partsInfo, }); console.log('result data:', res3.StatusCode); // 查询拷贝对象信息 const headResult = await client.headObject({ Bucket: dstBucket, Key: dstObject, }); console.log('headResult: ', headResult.ContentLength); } catch (error) { handleError(error); } } main();