对象大于 5GiB 时,需要进行分片拷贝。
以下代码用于分片拷贝对象。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> </head> <body> <button id="upload">上传</button> <button id="copy">复制</button> <input id="file" type="file" /> <!-- 导入 SDK 文件 --> <script src="https://tos-public.volccdn.com/obj/volc-tos-public/@volcengine/tos-sdk@latest/browser/tos.umd.production.min.js"></script> <script type="text/javascript"> const client = new TOS({ // yourRegion 填写Bucket 所在地域。以华北2(北京)为例,yourRegion 填写为 cn-beijing。 region: yourRegion, // 填写 endpoint 名称。 endpoint: yourEndpoint, // 从 STS 服务获取的临时访问密钥(AccessKey ID 和 AccessKey Secret)。 accessKeyId: yourAccessKey, accessKeySecret: yourSecretKey, // 从 STS 服务获取的安全令牌(SecurityToken)。 stsToken: yourSecurityToken, // 填写 Bucket 名称。 bucket: examplebucket, }); const srcBucket = yourSrcBucket; // 源桶 const srcObject = 'exampledir/putObject-test'; // 源对象 const dstBucket = yourDstBucket; // 目标桶 const dstObject = 'exampledir/part-copy-test'; // 目标对象 // 上传文件 const upload = document.getElementById('upload'); upload.addEventListener('click', async () => { // 从输入框获取 file 对象,例如 <input type="file" id="file" />。 const data = document.getElementById('file').files[0]; try { await client.uploadFile({ bucket: srcBucket, key: srcObject, file: data, }); } catch (e) { console.log(e); } }); // 复制文件 const copy = document.getElementById('copy'); copy.addEventListener('click', async () => { try { // 获取上传任务 ID const { data: { UploadId }, } = await client.createMultipartUpload({ bucket: dstBucket, key: dstObject, }); console.log('UploadId', UploadId); // 获取桶源桶中已存在对象的大小 const { data: { 'content-length': contentLength }, } = await client.headObject({ bucket: srcBucket, key: srcObject, }); console.log('srcObject content-length', contentLength); // 文件总大小 const totalSize = contentLength; const partSize = 5 * 1024 * 1024; let offset = 0; let partNumber = 1; const partsInfo = []; while (offset < totalSize) { // 上传分片拷贝 const uploadResult = await client.uploadPartCopy({ bucket: dstBucket, key: dstObject, partNumber, uploadId: UploadId, headers: { 'x-tos-copy-source': `/${srcBucket}/${srcObject}`, 'x-tos-copy-source-range': `bytes=${offset}-${offset + partSize}`, }, }); const eTag = uploadResult.data.ETag; console.log(`partNumber${partNumber} Etag:`, eTag); partsInfo.push({ partNumber, eTag, }); partNumber++; offset += partSize; } console.log('parts information', partsInfo); // 完成分片上传 const { data } = await client.completeMultipartUpload({ bucket: dstBucket, key: dstObject, uploadId: UploadId, parts: partsInfo, }); console.log('result data:', data); } catch (e) { console.log(e); } }); </script> </body> </html>