# aws-sdk-js-v3 **Repository Path**: openharmony-tpc-incubate/aws-sdk-js-v3 ## Basic Information - **Project Name**: aws-sdk-js-v3 - **Description**: No description available - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: bump-0.33.0 - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 3 - **Created**: 2025-08-04 - **Last Updated**: 2025-09-08 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # @aws-sdk/client-s3 ## 简介 @aws-sdk/client-s3 是 AWS SDK for JavaScript v3(ArkTs)提供的Amazon S3(Simple Storage Service)客户端库,用于ArkTs app与 AWS S3 服务进行交互。它允许开发者以 ​类型安全(TypeScript 支持)​​ 的方式执行 S3 操作,如上传、下载、删除文件,管理存储桶等。 ## 安装教程 ``` ohpm install @aws-sdk/client-s3 ``` OpenHarmony ohpm环境配置等更多内容,请参考 [如何安装OpenHarmony ohpm包](https://gitcode.com/openharmony-tpc/docs/blob/master/OpenHarmony_har_usage.md) 。 ## 使用说明 ### 初始化 S3 客户端 ``` import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; // 初始化 S3 客户端 export const REGION_1 = 'ap-northeast-1' export const REGION_2 = 'ap-northeast-1' export const FILE_1 = 'IMG_1750817551_001.jpg' export const MULTIPART_UPLOAD_IMAGE = 'multipart_upload_image.jpg' // 你的 S3 存储桶名称(替换成你的) export const BUCKET_NAME_1 = "YOUR_BUCKET_1"; //存储桶1 export const BUCKET_NAME_2 = "YOUR_BUCKET_2"; //存储桶2 export const s3Client = new S3Client({ region: "us-east-1", // 替换为你的 AWS 区域 credentials: { accessKeyId: "YOUR_ACCESS_KEY", // 替换为你的 AWS 凭证 secretAccessKey: "YOUR_SECRET_KEY", }, }); ``` ### 对象操作(Object Operations) 1. PutObjectCommand 上传对象(文件)到 S3 ``` putObjectCommand = async () => { let fileBuffer= await selectPhoto() if (!fileBuffer) { promptAction.showToast({message:'图片读取失败'}) return } const buf = fileBuffer[0] const uri = fileBuffer[1] const params: PutObjectCommandInput = { Bucket: BUCKET_NAME_1, Key: uri.substring(uri.lastIndexOf('/') + 1), // S3 上的文件名 Body: buf, // 文件内容 }; try { const command = new PutObjectCommand(params); const response = await s3Client.send(command); console.log('PutObjectCommand', "✅ 文件上传成功!", response); this.info = '文件上传成功!' } catch (error) { console.error('PutObjectCommand', "❌ 文件上传失败:", error); this.info = '文件上传失败:\n'+JSON.stringify(error) } } export async function selectPhoto() :Promise<[Uint8Array,string] | undefined>{ const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions(); photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE。 photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目。 const photoViewPicker = new photoAccessHelper.PhotoViewPicker(); let result = await photoViewPicker.select(photoSelectOptions) let uris = result?.photoUris if (!uris?.length) { return undefined } let u = uris[0] const buf = await readBufferFromUri(u) if (buf) { return [buf,u] }else{ return undefined } } // 1. 通过 URI 读取文件为 Buffer export async function readBufferFromUri(uri: string): Promise { try { // 2. 打开文件(URI 直接作为路径使用) let file = await fs.open(uri, fs.OpenMode.READ_ONLY); console.log('readBufferFromUri', `文件已打开,FD: ${file.fd}`); // 3. 获取文件大小 let stat = await fs.stat(file.fd); let fileSize = stat.size; console.log('readBufferFromUri', `文件大小: ${fileSize} 字节`); // 4. 读取文件内容到 Buffer let buffer = new ArrayBuffer(fileSize); let view = new Uint8Array(buffer); let bytesRead = await fs.read(file.fd, buffer); console.log('readBufferFromUri', `实际读取字节数: ${bytesRead}`); // 5. 关闭文件 await fs.close(file.fd); console.log('readBufferFromUri', '文件已关闭'); // 6. 返回 Buffer return view; } catch (error) { console.error('readBufferFromUri', '读取文件失败:', error); return undefined; } } ``` 2. GetObjectCommand 下载对象(文件)从 S3 ``` getObjectCommand = async () => { const params: GetObjectCommandInput = { Bucket: BUCKET_NAME_1, Key: FILE_1, }; try { const command: GetObjectCommand = new GetObjectCommand(params); const response = await s3Client.send(command); // 把 S3 的文件流写入本地文件 if (typeof response.Body === 'string' || response.Body instanceof ArrayBuffer) { await saveToDocument(FILE_1, response.Body) } this.info = '下载成功' } catch (error) { this.info = '下载失败 : ' + JSON.stringify(error) } } export function saveToDocument(filename: string, content: string | ArrayBuffer): Promise { return new Promise((resolve, reject) => { try { let documentSaveOptions = new picker.DocumentSaveOptions(); documentSaveOptions.newFileNames = [filename]; let documentPicker = new picker.DocumentViewPicker(getContext()); documentPicker.save(documentSaveOptions).then((documentSaveResult: Array) => { console.info('DocumentViewPicker.save successfully, documentSaveResult uri: ' + JSON.stringify(documentSaveResult)); let file = fs.openSync(documentSaveResult[0], fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); fs.writeSync(file.fd, content); fs.closeSync(file); resolve() }).catch((err: BusinessError) => { console.error(`DocumentViewPicker.save failed with err, code is: ${err.code}, message is: ${err.message}`); reject(err) }); } catch (error) { let err: BusinessError = error as BusinessError; console.error(`DocumentViewPicker failed with err, code is: ${err.code}, message is: ${err.message}`); reject(error) } }) } ``` 3. DeleteObjectCommand 删除 S3 中的对象 ``` deleteObjectCommand = async () => { const objectKey = "test.txt"; // 替换为你要查询的对象 Key const command = new DeleteObjectCommand({ Bucket: BUCKET_NAME_1, Key: objectKey, }); try { const response = await s3Client.send(command); this.info = '删除成功\n' this.info += JSON.stringify(response) } catch (error) { this.info = '删除失败\n' this.info += JSON.stringify(error) } } ``` 4. CopyObjectCommand 复制 S3 中的对象 ``` copyObjectCommand = async () => { // 2️⃣ 定义源 Bucket、源对象 Key,以及目标 Bucket 和目标对象 Key const sourceBucket = BUCKET_NAME_1; // 替换为源 Bucket 名称 const sourceKey = "test.txt"; // 替换为源对象 Key const destinationBucket = BUCKET_NAME_2; // 替换为目标 Bucket 名称 const destinationKey = "test.txt"; // 替换为目标对象 Key(可相同也可不同) // 3️⃣ 创建 CopyObjectCommand 实例 const copyObjectCommand = new CopyObjectCommand({ Bucket: destinationBucket, // 目标 Bucket 名称 Key: destinationKey, // 目标对象 Key CopySource: `${sourceBucket}/${sourceKey}`, // 源 Bucket 和 Key,格式为 "源Bucket/源Key" // 可选:设置目标对象的 Metadata 或 StorageClass 等 // MetadataDirective: 'REPLACE', // 可选:是否替换元数据,默认是 'COPY'(继承源对象的元数据) // Metadata: { // 可选:自定义元数据(仅在 MetadataDirective 为 'REPLACE' 时生效) // 'author': 'John Doe', // 'description': 'Copied file', // }, // StorageClass: 'STANDARD', // 可选:设置存储类别,如 'STANDARD', 'GLACIER' 等 }); try { const response = await s3Client.send(copyObjectCommand); this.info = '' this.info += `对象复制成功!\n`; this.info += `- 源: Bucket="${sourceBucket}", Key="${sourceKey}" \n`; this.info += `- 目标: Bucket="${destinationBucket}", Key="${destinationKey}" \n`; this.info += JSON.stringify(response) // CopyObject 通常没有太多返回信息,成功即表示复制完成 promptAction.showToast({ message: '对象复制成功' }) } catch (error) { console.error("❌ 对象复制失败:", error.message); this.info = '对象复制失败 : '+JSON.stringify(error) // 常见错误: // - NoSuchKey: 源对象不存在 // - NoSuchBucket: 源或目标 Bucket 不存在 // - AccessDenied: 权限不足 // - InvalidRequest: CopySource 格式错误或其他参数问题 } } ``` 5. HeadObjectCommand 获取对象的元数据(不下载内容) ``` click = async () => { const objectKey = "test.txt"; // 替换为你要查询的对象 Key const headObjectCommand = new HeadObjectCommand({ Bucket: BUCKET_NAME_1, Key: objectKey, }); try { const response: HeadObjectCommandOutput = await s3Client.send(headObjectCommand this.headInfo = '' this.headInfo += `✅ 成功获取对象 "${objectKey}" 的元数据:\n` this.headInfo += `- Size: ${response.ContentLength} 字节 \n`; this.headInfo += `- LastModified: ${response.LastModified} \n`; this.headInfo += `- ETag: ${response.ETag} \n`; // 文件内容的 MD5 哈希值(带引号) this.headInfo += `- ContentType: ${response.ContentType || '未设置'} \n`; // 文件的 M // 还可以访问其他元数据,如 Metadata、StorageClass 等 if (response.Metadata) { this.headInfo += `自定义 Metadata:${JSON.stringify(response.Metadata)} \n`; } if (response.StorageClass) { this.headInfo += `- StorageClass: ${response.StorageClass} \n`; // 存储类别,如 STA } } catch (error) { console.error("❌ 获取对象元数据失败:", error.message); this.headInfo = '获取对象元数据失败' // 常见错误: // - NoSuchKey: 对象不存在 // - NoSuchBucket: Bucket 不存在 // - AccessDenied: 权限不足 } } ``` 6. ListObjectsV2Command 列出存储桶中的对象 ``` click = async () => { const params: ListObjectsV2CommandInput = { Bucket: BUCKET_NAME_1, }; this.messageList = [] try { const command = new ListObjectsV2Command(params); const response = await s3Client.send(command); if (response.Contents) { response.Contents.forEach((value) => { this.messageList.push(`name : ${value.Key} \nsize : ${value.Size} bytes`) }) } else { this.messageList.push('存储桶是空的') } } catch (error) { console.error('ListObjectsV2Command', "❌ 列出文件失败:", error); this.messageList.push('列出文件失败 : '+JSON.stringify(error)) } } ``` 7. ListObjectsCommand 列出存储桶中的对象(旧版,不推荐) ``` click = async () => { const params: ListObjectsCommandInput = { Bucket: BUCKET_NAME_1, // 可选参数(按需添加) Delimiter: "/", // 分隔符(用于分组对象) EncodingType: "url", // 编码类型(url 或空字符串) Marker: "prefix/", // 分页标记(用于分页查询) MaxKeys: 1000, // 最大返回对象数(默认 1000) // Prefix: "folder/" // 前缀(筛选特定路径下的对象) }; try { const command: ListObjectsCommand = new ListObjectsCommand(params const response = await s3Client.send(command); let result = 'response object: ' + response.Contents console.log(TAG, result); // 返回的对象列表 if (response.Contents) { response.Contents.forEach((value) => { this.messageList.push(`name : ${value.Key} \nsize : ${value.S }) } else { this.messageList.push('存储桶是空的') } } catch (error) { this.messageList.push('列出文件失败 : \n' + JSON.stringify(error)) } } ``` 8. RestoreObjectCommand 恢复存档存储中的对象 ``` click = async () => { try { // 先需要修改存档存储 const copyCommand = new CopyObj Bucket: BUCKET_NAME_1, Key: this.resultkey, CopySource: BUCKET_NAME_1 + " StorageClass: "GLACIER", // 或 }); await s3Client.send(copyCommand this.info += '1.先设置一个对象为存档存储\n' // 定义参数 const params: RestoreObjectComm Bucket: BUCKET_NAME_1, // 存储桶 Key: this.resultkey, // 对象键名( RestoreRequest: { // 恢复请求配置(必需) Days: 1, // 恢复对象的保留天数(1-30 GlacierJobParameters: { // Glacier 恢复参数(可选) // Tier: "Expedited" | "S Tier: 'Standard' }, }, }; // 执行命令 const restoreCommand = new Rest await s3Client.send(restoreComm console.log(TAG, "恢复任务已提交"); this.info += '2.恢复对象\n' // 2. 检查恢复状态(可选) const headCommand = new HeadObj const headResponse = await s3Cl console.log(TAG, "对象状态:", headR this.info += '3.RestoreObjectCo } catch (e) { this.info += '操作异常' + JSON.stri } } ``` 9. PutObjectAclCommand 设置对象的访问控制列表(ACL) ``` click = async () => { const params: PutObjectAclCommandInput = { Bucket: BUCKET_NAME_1, Key: FILE_1, ACL: ObjectCannedACL.public_read }; const command = new PutObjectAclCommand(params); s3Client.send(command) .then(() => { this.info = 'ACL updated successfully' promptAction.showToast({ message: 'ACL updated successfully' }) }) .catch((err: BusinessError) => { this.info = `Error updating ACL: ${JSON.stringify(err)}` promptAction.showToast({ message: 'Error updating ACL:' }) console.log(TAG,JSON.stringify(err)) }); } ``` 10. GetObjectAclCommand 获取对象的访问控制列表(ACL) ``` click = async () => { const params: GetObjectAclCommandInput = { Bucket: BUCKET_NAME_1, Key: FILE_1, }; // 3. 创建命令 const command = new GetObjectAclCommand(params); // 4. 执行命令 s3Client.send(command) .then((data) => { this.info += "对象的 ACL 信息:\n" this.info += JSON.stringify(data) }) .catch((error:BusinessError) => { this.info += '获取 ACL 失败:\n' this.info += JSON.stringify(error) }); } ``` 11. PutObjectTaggingCommand 设置对象的标签 ``` click = async () => { // 设置标签的参数 const params: PutObjectTaggingCommandInput = { Bucket: BUCKET_NAME_1, Key: FILE_1, Tagging: { TagSet: [// 标签集合(可多个) { Key: "Environment", Value: "Production" }, { Key: "Project", Value: "MyApp" }, ], }, }; // 创建命令并执行 const command = new PutObjectTaggingCommand(params); s3Client.send(command) .then(() => { this.info = 'Tags added successfully' promptAction.showToast({ message: 'Tags added successfully' }) }) .catch((err: BusinessError) => { this.info = "Error adding tags:" + JSON.stringify(err) promptAction.showToast({ message: "Error adding tags:" + JSON.stringify(err) }) }); } ``` 12. GetObjectTaggingCommand 获取对象的标签 ``` click = async () => { // 获取标签的参数 const params : GetObjectTaggingCommandIn Bucket: BUCKET_NAME_1, Key: FILE_1, }; // 创建命令并执行 const command = new GetObjectTaggingComm s3Client.send(command) .then((response) => { const tags = response.TagSet; // 获取 console.log("Object Tags:", tags); this.info = `Object Tags:${JSON.stri // 示例输出:[{ Key: 'Environment', Value }) .catch((err: BusinessError) => { this.info = `Error fetching tags: ${ console.error("Error fetching tags:" }); } ``` 13. DeleteObjectTaggingCommand 删除对象的标签 ``` click = async () => { // 获取标签的参数 const params : DeleteObjectTaggingCommandInput = { Bucket: BUCKET_NAME_1, Key: FILE_1, }; // 创建命令并执行 const command = new DeleteObjectTaggingCommand(params); s3Client.send(command) .then(() => this.info = ("Tags deleted successfully")) .catch((err : BusinessError) => this.info = "Error deleting tags: \n" + JSON.stringify(err)); } ``` 14. PutObjectLegalHoldCommand 设置对象的合法保留状态 ``` click = async () => { // 设置法律保留的参数 const params : PutObjectLegalHoldCommandInput = { Bucket: BUCKET_NAME_1, // 存储桶名称 Key: FILE_1, // 对象键(文件名) LegalHold: { // ObjectLockLegalHold Status: "ON" } }; // 创建命令并执行 const command = new PutObjectLegalHoldCommand(params); s3Client.send(command) .then(() => { this.info = 'Legal Hold set successfully' console.log(TAG, "Legal Hold set successfully") }) .catch((err: BusinessError) => { this.info = `Error setting Legal Hold: ${JSON.stringify(err)}` console.error(TAG, "Error setting Legal Hold:", err) }); } ``` 15. GetObjectLegalHoldCommand 获取对象的合法保留状态 ``` click = async () => { // 设置法律保留的参数 const params : GetObjectLegalHoldCommandInput = { Bucket: BUCKET_NAME_1, // 存储桶名称 Key: FILE_1, // 对象键(文件名) }; // 创建命令并执行 const command = new GetObjectLegalHoldCommand(params); s3Client.send(command) .then((response) => { const legalHoldStatus = response.LegalHold?.Status; // 获取法律保留状态 this.info = `Legal Hold Status: ${legalHoldStatus}` console.log("Legal Hold Status:", legalHoldStatus); // 输出 "ON" 或 "OFF"(或 undefined 如果未设置) }) .catch((err: BusinessError) => { this.info = `Error fetching Legal Hold status: ${JSON.stringify(err)}` console.error("Error fetching Legal Hold status:", err) }); } ``` ### 对象操作(Object Operations) 1. CreateBucketCommand 创建 S3 存储桶 ``` click = async () => { const createBucketCommand = new CreateBucketCommand({ Bucket: BUCKET_NAME_2, // 可选:如果你在中国区,需要指定 CreateBucketConfiguration // CreateBucketConfiguration: { // LocationConstraint: "ap-northeast-1", // }, // 可选:设置 ACL(访问控制列表),如 'private', 'public-read' 等 // ACL: 'private', // 默认是 private }); try { const response = await s3Client.send(createBucketCommand); promptAction.showToast({ message: 'Bucket 创建成功!' }) this.info = 'Bucket 创建成功!' // response 中可能包含 Location 等信息,但通常 Bucket 名称已足够确认 } catch (error) { this.info = 'Bucket 创建失败:\n'+JSON.stringify(error) } } ``` 2. DeleteBucketCommand 删除 S3 存储桶 ``` click = async () => { const deleteBucketCommand = new DeleteBucketCommand({ Bucket: BUCKET_NAME_2, }); try { const response = await s3Client.send(deleteBucketCommand); this.info = 'Bucket 删除成功!' } catch (error) { this.info = 'Bucket 删除失败:\n' + JSON.stringify(error) } } ``` 3. ListBucketsCommand 列出所有存储桶 ``` click = async () => { // 2. 创建命令(ListBuckets 不需要参数) const command = new ListBucket // 3. 执行命令 s3Client.send(command) .then((data:ListBucketsComma this.info += "你的 S3 存储桶列表: data.Buckets?.forEach((buc this.info += `- ${bucket }); }) .catch((error:BusinessError) this.info += "列出存储桶失败:" + }); } ``` 4. GetBucketLocationCommand 获取存储桶的位置(区域) ``` click = async () => { const params : GetBucketLocationCommandInput = { Bucket: BUCKET_NAME_1, // 替换为你的存储桶名称 }; // 2. 创建命令(ListBuckets 不需要参数) const command = new GetBucketLocationCommand(params); // 3. 执行命令 s3Client.send(command) .then((data:GetBucketLocationCommandOutput) => { this.info += "你的 S3 存储桶列表:\n"; const location = data.LocationConstraint || REGION_1; // 如果返回 null,表示 us-east-1 this.info += `存储桶 "${params.Bucket}" 的地理位置是: ${location}`; }) .catch((error:BusinessError) => { this.info += "获取存储桶位置失败:" + JSON.stringify(error); }); } ``` 5. PutBucketAclCommand 设置存储桶的访问控制列表(ACL) ``` click = async () => { const params: PutBucketAclCommandInput = { Bucket: BUCKET_NAME_1, ACL: ObjectCannedACL.public_read }; const command = new PutBucketAclCommand(params); s3Client.send(command) .then(() => { this.info = 'ACL updated successfully' promptAction.showToast({ message: 'ACL updated successfully' }) }) .catch((err: BusinessError) => { this.info = `Error updating ACL: ${JSON.stringify(err)}` promptAction.showToast({ message: 'Error updating ACL:' }) console.log(TAG,JSON.stringify(err)) }); } ``` 6. GetBucketAclCommand 获取存储桶的访问控制列表(ACL) ``` click = async () => { const params: GetBucketAclCommandInput = { Bucket: BUCKET_NAME_1, }; // 3. 创建命令 const command = new GetBucketAclCommand(params); // 4. 执行命令 s3Client.send(command) .then((data) => { this.info += "对象的 ACL 信息:\n" this.info += JSON.stringify(data) }) .catch((error:BusinessError) => { this.info += '获取 ACL 失败:\n' this.info += JSON.stringify(error) }); } ``` 7. PutBucketPolicyCommand 设置存储桶的策略(Policy) ``` click = async () => { // 2. 配置参数(设置允许公开读取的策略) class statement { Effect? :string Principal?: string Action?:string Resource?:string } let a : statement = { Effect: "Allow", Principal: "*", // 允许所有用户(包括匿名访问) Action: "s3:GetObject", // 允许读取对象 Resource: "arn:aws:s3:::hydongjing/*" // 存储桶中的所有对象 } const params : PutBucketPolicyCommandInput = { Bucket: BUCKET_NAME_1, // 替换为你的存储桶名称 Policy: JSON.stringify({ Version: "2012-10-17", Statement: [ a ] }) }; // 3. 创建命令 const command = new PutBucketPolicyCommand(params); // 4. 执行命令 s3Client.send(command) .then((data:PutBucketPolicyCommandOutput) => { this.info += "存储桶策略设置成功!"; }) .catch((error:BusinessError) => { this.info += "设置存储桶策略失败:" + JSON.stringify(error); }); } ``` 8. GetBucketPolicyCommand 获取存储桶的策略(Policy) ``` click = async () => { const params: GetBucketPolicyCommandInput = { Bucket: BUCKET_NAME_1, }; const command = new GetBucketPolicyCommand(params); s3Client.send(command) .then((data:GetBucketPolicyCommandOutput) => { this.info += '存储桶的策略内容:\n' this.info += data.Policy }) .catch((err: BusinessError) => { this.info += '存储桶的策略内容 error:\n' this.info += JSON.stringify(err) }); } ``` 9. DeleteBucketPolicyCommand 删除存储桶的策略(Policy) ``` click = async () => { // 3. 创建 DeleteBucketPolicyCommand const deleteBucketPolicyCommand = new DeleteBucketPolicyCommand({ Bucket: BUCKET_NAME_1 }); // 4. 执行命令 try { const response = await s3Client.send(deleteBucketPolicyCommand); this.info += '存储桶策略已成功删除\n' this.info += '响应\n' this.info += JSON.stringify(response) } catch (error) { this.info += '删除存储桶策略时出错\n' this.info += JSON.stringify(error) } } ``` 10. PutBucketCorsCommand 设置存储桶的跨域资源共享(CORS) ``` click = async () => { let rs: CORSRule = { AllowedHeaders: ["*"], // 允许所有请求头 AllowedMethods: ["GET", "POST", "PUT", "DELETE", "HEAD"], // 允许的 HTTP 方法 AllowedOrigins: ["*"], // 允许所有来源(生产环境应限制为特定域名) ExposeHeaders: ["ETag"], // 暴露的响应头 MaxAgeSeconds: 3000 // 预检请求缓存时间(秒) } let rules: CORSConfiguration = { CORSRules: [rs] } // 3. 定义 CORS 配置 const corsConfiguration: PutBucketCorsCommandInput = { Bucket: BUCKET_NAME_1, CORSConfiguration: rules }; // 4. 创建 PutBucketCorsCommand const putBucketCorsCommand = new PutBucketCorsCommand(corsConfiguration); // 5. 执行命令 try { const response = await s3Client.send(putBucketCorsCommand); this.info += "存储桶 CORS 配置已成功设置\n"; this.info += "响应:\n" this.info += JSON.stringify(response); } catch (error) { this.info += "设置存储桶 CORS 配置时出错:\n" this.info += JSON.stringify(error); } } ``` 11. GetBucketCorsCommand 获取存储桶的跨域资源共享(CORS) ``` click = async () => { // 3. 创建 GetBucketCorsCommand const getBucketCorsCommand = new GetBucketCorsCommand({ Bucket: BUCKET_NAME_1 }); // 4. 执行命令 try { const response = await s3Client.send(getBucketCorsCommand); if (response.CORSRules && response.CORSRules.length > 0) { this.info += "存储桶 CORS 配置:\n"; this.info += JSON.stringify(response.CORSRules, null, 2) } else { this.info += "存储桶没有配置 CORS 规则"; } } catch (error) { if (error.name === "NoSuchBucketPolicy") { this.info += "存储桶没有配置 CORS 规则"; } else { this.info += "获取存储桶 CORS 配置时出错:\n" this.info += JSON.stringify(error); } } } ``` 12. DeleteBucketCorsCommand 删除存储桶的跨域资源共享(CORS) ``` click = async () => { // 3. 创建 DeleteBucketCorsCommand const deleteBucketCorsCommand = new DeleteBucketCorsCommand({ Bucket: BUCKET_NAME_1 }); // 4. 执行命令 try { const response = await s3Client.send(deleteBucketCorsCommand); this.info += '存储桶 CORS 配置已成功删除\n' this.info += '响应:\n' this.info += JSON.stringify(response) } catch (error) { if (error.name === "NoSuchBucketPolicy") { this.info += "存储桶没有配置 CORS 规则(无需删除)"; } else { this.info += "删除存储桶 CORS 配置时出错:" this.info += JSON.stringify(error); } } } ``` 13. PutBucketLifecycleConfigurationCommand 设置存储桶的生命周期规则 ``` click = async () => { // 3. 定义生命周期配置规则 const lifecycleConfiguration:BucketLifecycleConfiguration = { Rules: [ { ID: "MoveToGlacierAfter30Days", // 规则唯一标识符 Status: "Enabled", // 规则状态:Enabled 或 Disabled Filter: { Prefix: "logs/", // 可选:只应用于特定前缀的对象 // Tags: [ // 可选:只应用于带有特定标签的对象 // { Key: "env", Value: "production" } // ] }, Transitions: [ { Days: 30, // 对象在存储桶中存放30天后 StorageClass: "GLACIER" // 转换为GLACIER存储类 } ], Expiration: { Days: 365 // 对象在存储桶中存放365天后过期删除 } }, { ID: "DeleteOldBackups", // 另一个规则示例 Status: "Enabled", Filter: { Prefix: "backups/" }, Expiration: { Days: 90 // 备份文件90天后过期删除 } } ] }; // 4. 创建 PutBucketLifecycleConfigurationCommand const putBucketLifecycleCommand = new PutBucketLifecycleConfigurationCommand({ Bucket: BUCKET_NAME_1, LifecycleConfiguration: lifecycleConfiguration }); // 5. 执行命令 try { const response = await s3Client.send(putBucketLifecycleCommand); this.info += "存储桶生命周期配置已成功设置\n"; this.info += "响应:\n" this.info += JSON.stringify(response); } catch (error) { this.info += "设置存储桶生命周期配置时出错:\n" this.info += JSON.stringify(error); } } ``` 14. GetBucketLifecycleConfigurationCommand 获取存储桶的生命周期规则 ``` click = async () => { // 3. 创建 GetBucketLifecycleConfigurationCommand const getBucketLifecycleCommand = new GetBucketLifecycleConfigurationCommand({ Bucket: BUCKET_NAME_1 }); // 4. 执行命令 try { const response: GetBucketLifecycleConfigurationCommandOutput = await s3Client.send(getBucketLifecycleCommand); if (response.Rules && response.Rules.length > 0) { this.info += "存储桶生命周期配置:\n"; this.info += JSON.stringify(response.Rules); } else { this.info += "存储桶没有配置生命周期规则"; } } catch (error) { if (error.name === "NoSuchLifecycleConfiguration") { this.info += "存储桶没有配置生命周期规则"; } else { this.info += "获取存储桶生命周期配置时出错:" this.info += JSON.stringify(error); } } } ``` 15. PutBucketVersioningCommand 设置存储桶的版本控制 ``` click = async () => { // 3. 定义版本控制配置 const versioningConfiguration :PutBucketVersioningCommandInput = { Bucket: BUCKET_NAME_1, VersioningConfiguration: { Status : "Enabled" } // 可选值:"Enabled" 或 "Suspended" }; // 4. 创建 PutBucketVersioningCommand const putBucketVersioningCommand = new PutBucketVersioningCommand(versioningConfiguration); // 5. 执行命令 try { const response = await s3Client.send(putBucketVersioningCommand); this.info += "存储桶版本控制已成功设置"; this.info += "响应:\n" this.info += JSON.stringify(response); } catch (error) { this.info += "设置存储桶版本控制时出错:\n" this.info += JSON.stringify(error); } } ``` 16. GetBucketVersioningCommand 获取存储桶的版本控制 ``` click = async () => { // 3. 创建 GetBucketVersioningCommand const getBucketVersioningCommand = new GetBucketVersioningC Bucket: BUCKET_NAME_1 }); // 4. 执行命令 try { const response = await s3Client.send(getBucketVersionin if (response.Status) { this.info += `存储桶版本控制状态: ${response.Status}\n`; // 解释状态含义 if (response.Status === "Enabled") { this.info += "版本控制已启用:所有对象操作都会创建新版本\n"; } else if (response.Status === "Suspended") { this.info += "版本控制已暂停:已存在的版本会被保留,但新操作不会创建新版本\n"; } } else { this.info += "存储桶没有配置版本控制(可能是未设置或设置为 Suspended)"; } } catch (error) { if (error.name === "NoSuchBucketPolicy") { this.info += "存储桶没有配置版本控制(可能是未设置或设置为 Suspended)"; } else { this.info += "获取存储桶版本控制状态时出错:\n" this.info += JSON.stringify(error); } } } ``` 17. PutBucketWebsiteCommand 设置存储桶的静态网站托管 ``` click = async () => { // 3. 定义静态网站配置 const websiteConfiguration: WebsiteConfiguration = { IndexDocument: { Suffix: "index.html" // 网站首页文件名(默认为 index.html) }, ErrorDocument: { Key: "error.html" // 错误页面文件名(当请求的资源不存在时返回) } }; // 4. 创建 PutBucketWebsiteCommand const putBucketWebsiteCommand = new PutBucketWebsiteCommand({ Bucket: BUCKET_NAME_1, WebsiteConfiguration: websiteConfiguration }); // 5. 执行命令 try { const response = await s3Client.send(putBucketWebsiteCommand); this.info += "存储桶静态网站托管已成功设置\n"; this.info += "响应:\n" this.info += JSON.stringify(response); } catch (error) { this.info += "设置存储桶静态网站托管时出错:\n" this.info += JSON.stringify(JSON.stringify(error)); } } ``` 18. GetBucketWebsiteCommand 获取存储桶的静态网站托管 ``` click = async () => { // 3. 创建 GetBucketWebsiteCommand const getBucketWebsiteCommand = new GetBucketWebsiteCommand({ Bucket: BUCKET_NAME_1 }); // 4. 执行命令 try { const response = await s3Client.send(getBucketWebsiteCommand); if (response.IndexDocument && response.ErrorDocument) { this.info += "存储桶静态网站托管配置:\n"; this.info += `- 首页文件: ${response.IndexDocument.Suffix}\n`; this.info += `- 错误页面: ${response.ErrorDocument.Key}\n`; // 如果有重定向配置 if (response.RedirectAllRequestsTo) { this.info += `- 重定向目标: ${response.RedirectAllRequestsTo.HostName}\n` this.info += `- 协议: ${response.RedirectAllRequestsTo.Protocol}\n`; } // 如果有路由规则 if (response.RoutingRules && response.RoutingRules.length > 0) { this.info += "路由规则:\n"; response.RoutingRules.forEach((rule, index) => { this.info += ` 规则 ${index + 1}:\n`; if (rule.Condition && rule.Condition.KeyPrefixEquals) { this.info += ` - 匹配路径前缀: ${rule.Condition.KeyPrefixEquals}\n` } if (rule.Redirect) { this.info += ` - 重定向到: ${rule.Redirect.HostName}\n`; if (rule.Redirect.ReplaceKeyPrefixWith) { this.info += ` - 替换路径前缀: ${rule.Redirect.ReplaceKeyPrefix } } }); } } else { this.info += "存储桶没有配置静态网站托管\n"; } } catch (error) { if (error.name === "NoSuchWebsiteConfiguration") { this.info += "存储桶没有配置静态网站托管\n"; } else { this.info += "获取存储桶静态网站托管配置时出错:\n" this.info += JSON.stringify(error); } } } ``` 19. DeleteBucketWebsiteCommand 删除存储桶的静态网站托管 ``` click = async () => { // 3. 创建 DeleteBucketWebsiteCommand const deleteBucketWebsiteCommand = new DeleteBucketW Bucket: BUCKET_NAME_1 }); // 4. 执行命令 try { const response = await s3Client.send(deleteBucke this.info += "存储桶静态网站托管配置已成功删除\n"; this.info += "响应:\n" this.info += JSON.stringify(response); } catch (error) { if (error.name === "NoSuchWebsiteConfiguration") this.info += "存储桶没有配置静态网站托管(无需删除)"; } else { this.info += "删除存储桶静态网站托管配置时出错:\n" this.info += JSON.stringify(error); } } } ``` 20. PutBucketEncryptionCommand 设置存储桶的服务器端加密(SSE) ``` click = async () => { // 3. 定义加密配置 const serverSideEncryptionConfiguration : ServerSideEncryptionConfiguration= { Rules: [ { ApplyServerSideEncryptionByDefault: { SSEAlgorithm: "AES256" // 或 "aws:kms"(使用 AWS KMS) // 如果使用 "aws:kms",还需要指定 KMS 密钥 ID: // KMSMasterKeyID: "arn:aws:kms:region:account-id:key/key-id" } } ] }; // 4. 创建 PutBucketEncryptionCommand const putBucketEncryptionCommand = new PutBucketEncryptionCommand({ Bucket: BUCKET_NAME_1, ServerSideEncryptionConfiguration: serverSideEncryptionConfiguration }); // 5. 执行命令 try { const response = await s3Client.send(putBucketEncryptionCommand); this.info += "存储桶服务器端加密配置已成功设置\n"; this.info += "响应:\n" this.info += JSON.stringify(response); } catch (error) { if (error.name === "NoSuchBucketPolicy") { this.info += "存储桶没有配置加密规则(可能是未设置或设置为 Suspended)"; } else { this.info += "设置存储桶服务器端加密配置时出错:\n" this.info += JSON.stringify(error); } } } ``` 21. GetBucketEncryptionCommand 获取存储桶的服务器端加密(SSE) ``` click = async () => { // 3. 创建 GetBucketEncryptionCommand const getBucketEncryptionCommand = new GetBucketEncryptionCommand({ Bucket: BUCKET_NAME_1 }); // 4. 执行命令 try { const response = await s3Client.send(getBucketEncryptionCommand); if (response.ServerSideEncryptionConfiguration && response.ServerSideEncryptionConfiguration.Rules) this.info += "存储桶服务器端加密配置:\n"; this.info += JSON.stringify(response.ServerSideEncryptionConfiguration, null, 2); this.info += '\n"' // 解释加密配置 const rule = response.ServerSideEncryptionConfiguration.Rules[0]; const algorithm = rule.ApplyServerSideEncryptionByDefault?.SSEAlgorithm; this.info += `- 加密算法: ${algorithm}\n`; if (algorithm === "aws:kms") { this.info += `- KMS 密钥 ID: ${rule.ApplyServerSideEncryptionByDefault?.KMSMasterKeyID}\n`; } } else { this.info += "存储桶没有配置服务器端加密\n"; } } catch (error) { if (error.name === "ServerSideEncryptionConfigurationNotFoundError") { this.info += "存储桶没有配置服务器端加密\n"; } else { this.info += "获取存储桶服务器端加密配置时出错:\n" this.info += JSON.stringify(error); } } } ``` 22. DeleteBucketEncryptionCommand 删除存储桶的服务器端加密(SSE) ``` click = async () => { // 3. 创建 DeleteBucketEncryptionCommand const deleteBucketEncryptionCommand = new DeleteBucketEncryptionCommand({ Bucket: BUCKET_NAME_1 }); // 4. 执行命令 try { const response = await s3Client.send(deleteBucketEncryptionCommand); this.info += "存储桶服务器端加密配置已成功删除\n"; this.info += "响应:\n" this.info += JSON.stringify(response); } catch (error) { if (error.name === "ServerSideEncryptionConfigurationNotFoundError") { this.info += "存储桶没有配置服务器端加密(无需删除)\n"; } else { this.info += "删除存储桶服务器端加密配置时出错:\n" this.info += JSON.stringify(error); } } } ``` ### 分片上传 1. CreateMultipartUploadCommand 初始化分片上传 ``` createMultipartUploadCommand = async () => { try { this.imageBuffer = this.context.resourceManager.getRawFileContentSync(MULTIPART_UPLOAD_IMAGE) const input: CreateMultipartUploadCommandInput = { Bucket: BUCKET_NAME_1, Key: MULTIPART_UPLOAD_IMAGE, ContentType: contentType }; const command = new CreateMultipartUploadCommand(input); const response = await s3Client.send(command); if (response.UploadId) { this.addMessage('分片上传初始化成功 UploadId = ' + response.UploadId) this.uploadId = response.UploadId this.partCount = Math.ceil(this.imageBuffer.byteLength / partSize); } else { this.addMessage('分片上传初始化失败 UploadId undefined ') } } catch (error) { console.error("❌ 分片上传初始化失败:", JSON.stringify(error)); this.addMessage('分片上传初始化失败') // 常见错误: // - NoSuchKey: 源对象不存在 // - NoSuchBucket: 源或目标 Bucket 不存在 // - AccessDenied: 权限不足 // - InvalidRequest: CopySource 格式错误或其他参数问题 } } ``` 2. UploadPartCommand 上传分片 ``` uploadPartCommand = async () => { if (!this.imageBuffer) { this.addMessage('文件数据获取失败') return } const start = this.partUploadCursor * partSize; const end = Math.min(start + partSize, this.imageBuffer.byteLength); const partData = this.imageBuffer.slice(start, end) try { // let task = new taskpool.Task(uploadPart, this.uploadId!, this.partUploadCursor + 1, partData) // const response = await taskpool.execute(task) as UploadPartCommandOutput const response = await uploadPart(this.uploadId!, this.partUploadCursor + 1, partData) if (response.ETag) { this.completedParts.push({ ETag: response.ETag, PartNumber: this.partUploadCursor + 1 }) this.addMessage(`分片上传成功 partNumber = ${this.partUploadCursor + 1} Etag=${response.ETag}`) this.partUploadCursor++ } else { this.addMessage('分片上传失败:未生成ETag') } } catch (error) { console.error('uploadPartCommand', 'upload part error = ' + JSON.stringify(error) + ' message = ' + error.message) this.addMessage('分片上传失败') } } ``` 3. CompleteMultipartUploadCommand 完成分片上传 ``` completeMultipartUploadCommand = async () => { try { const sortedParts = this.completedParts.sort((a, b) => { const aNumber = a.PartNumber ?? 0 const bNumber = b.PartNumber ?? 0 return aNumber - bNumber }); const completeCommand = new CompleteMultipartUploadCommand({ Bucket: BUCKET_NAME_1, Key: MULTIPART_UPLOAD_IMAGE, UploadId: this.uploadId, MultipartUpload: { Parts: sortedParts } }); const response = await s3Client.send(completeCommand); this.addMessage('完成分片上传成功:' + response.Location); await this.resetUpload() } catch (error) { console.error('completeMultipartUploadCommand', '完成分片上传失败:' + JSON.stringify(error)); this.addMessage('完成分片上传失败'); } } ``` 4. AbortMultipartUploadCommand 取消分片上传 ``` abortMultipartUploadCommand = async () => { try { const abortCommand = new AbortMultipartUploadCommand({ Bucket: BUCKET_NAME_1, Key: MULTIPART_UPLOAD_IMAGE, UploadId: this.uploadId }); const response = await s3Client.send(abortCommand); this.addMessage('取消分片上传成功'); await this.resetUpload() } catch (error) { this.addMessage('取消分片上传失败'); console.error('abortMultipartUploadCommand', '取消分片上传失败:' + JSON.stringify(error)) } } ``` 5. ListMultipartUploadsCommand 列出分片上传任务 ``` listMultipartUploadsCommand = async () => { try { const command = new ListMultipartUploadsCommand({ Bucket: BUCKET_NAME_1, // Prefix: options.prefix, // MaxUploads: options.maxUploads, // Delimiter: options.delimiter }); const response = await s3Client.send(command); if (!response.Uploads) { this.addMessage('没有找到进行中的分片上传'); } else { let uploaderInfos = `找到 ${response.Uploads.length} 个进行中的上传任务:\n` response.Uploads.forEach(upload => { uploaderInfos += `- Key: ${upload.Key}\n`; uploaderInfos += ` Upload ID: ${upload.UploadId}\n`; uploaderInfos += ` Initiated: ${upload.Initiated}\n`; uploaderInfos += '------------------\n'; }); this.addMessage(uploaderInfos) } } catch (error) { console.error('列出分片上传时出错:' + JSON.stringify(error)); this.addMessage('列出分片上传时出错') } } ``` 6. ListPartsCommand 列出分片上传任务的各个部分 ``` listPartsCommand = async () => { try { const command = new ListPartsCommand({ Bucket: BUCKET_NAME_1, Key: MULTIPART_UPLOAD_IMAGE, UploadId: this.uploadId, // MaxParts: options.maxParts, // PartNumberMarker: options.partNumberMarker }); const response = await s3Client.send(command); if (!response.Parts) { this.addMessage('该上传任务没有找到任何分片'); } else { let partsInfo = `找到 ${response.Parts.length} 个分片:\n`; response.Parts.forEach(part => { partsInfo += `- 分片编号: ${part.PartNumber}\n`; partsInfo += ` ETag: ${part.ETag}\n`; partsInfo += ` 大小: ${part.Size} 字节\n`; partsInfo += ` 最后修改: ${part.LastModified}\n`; partsInfo += '------------------\n'; }); this.addMessage(partsInfo) } } catch (error) { console.error('listPartsCommand', '列取分片时出错:' + JSON.stringify(error)); this.addMessage('列取分片时出错'); } } ``` ### 其他操作 1. GetBucketLocationCommand 获取存储桶的区域 ``` click = async () => { // 3. 创建 GetBucketLocationCommand const getBucketLocationCommand = new GetBucketLocationCommand({ Bucket: BUCKET_NAME_1 }); // 4. 执行命令 try { const response = await s3Client.send(getBucketLocationCommand); if (response.LocationConstraint) { const region = response.LocationConstraint === null ? "us-east-1" : response.LocationConstraint; this.info += `存储桶 ${BUCKET_NAME_1} 位于 AWS 区域: ${region}`; } else { this.info += "无法获取存储桶位置信息"; } } catch (error) { if (error.name === "NoSuchBucket") { this.info += "存储桶不存在"; } else { this.info += "获取存储桶位置时出错:" this.info += JSON.stringify(error); } } } ``` 2. PutBucketLoggingCommand 设置存储桶的日志记录 ``` click = async () => { const sourceBucketName = BUCKET_NAME_1; const targetBucketName = BUCKET_NAME_2; // 1. 设置日志记录 const loggingConfiguration : BucketLoggingStatus = { LoggingEnabled: { TargetBucket: targetBucketName, TargetPrefix: "logs/" } }; const putCommand = new PutBucketLoggingCommand({ Bucket: sourceBucketName, BucketLoggingStatus: loggingConfiguration }); const response = await s3Client.send(putCommand); this.info += "日志记录已设置:\n"; this.info += JSON.stringify(response) } ``` 3. GetBucketLoggingCommand 获取存储桶的日志记录 ``` click = async () => { const sourceBucketName = BUCKET_NAME_1; const targetBucketName = BUCKET_NAME_2; let request : GetBucketLoggingCommandInput = { Bucket: sourceBucketName } // 2. 获取并验证配置 const getCommand : GetBucketLoggingCommand = new GetBucketLoggingCommand(request); const response : GetBucketLoggingCommandOutput = await s3Client.send(getCommand); this.info += "当前日志记录配置:\n" this.info += JSON.stringify(response); } ``` 4. PutBucketTaggingCommand 设置存储桶的标签 ``` click = async () => { // 3. 定义存储桶标签 const taggingConfiguration: Tagging = { TagSet: [ { Key: "Environment", // 标签键 Value: "Production" // 标签值 }, { Key: "Project", // 标签键 Value: "MyProject" // 标签值 }, { Key: "Owner", // 标签键 Value: "DevTeam" // 标签值 } ] }; // 4. 创建 PutBucketTaggingCommand const putBucketTaggingCommand = new PutBucketTaggingCommand({ Bucket: BUCKET_NAME_1, Tagging: taggingConfiguration }); // 5. 执行命令 try { const response = await s3Client.send(putBucketTaggingCommand); this.info += "存储桶标签已成功设置"; this.info += "响应:\n" this.info += JSON.stringify(response); } catch (error) { if (error.name === "NoSuchBucket") { this.info += "存储桶不存在"; } else if (error.name === "InvalidTag") { this.info += "标签无效(如键或值为空或超过限制)"; } else { this.info +="设置存储桶标签时出错:" this.info += JSON.stringify(error); } } } ``` 5. GetBucketTaggingCommand 获取存储桶的标签 ``` click = async () => { // 3. 创建 GetBucketTaggingCommand const getBucketTaggingCommand = new GetBucketTaggingCommand({ Bucket: BUCKET_NAME_1 }); // 4. 执行命令 try { const response = await s3Client.send(getBucketTaggingCommand); if (response.TagSet && response.TagSet.length > 0) { this.info += "存储桶标签配置:"; response.TagSet.forEach((tag, index) => { this.info += `标签 ${index + 1}:`; this.info += `- 键: ${tag.Key}`; this.info += `- 值: ${tag.Value}`; }); } else { this.info += "存储桶没有配置标签"; } } catch (error) { if (error.name === "NoSuchBucket") { this.info += "存储桶不存在"; } else if (error.name === "NoSuchBucketTagging") { this.info += "存储桶没有配置标签(可能是未设置或设置为 Suspended)"; } else { this.info += "获取存储桶标签时出错:" this.info += JSON.stringify(error); } } } ``` 6. DeleteBucketTaggingCommand 删除存储桶的标签 ``` click = async () => { // 3. 创建 DeleteBucketTaggingCommand const deleteBucketTaggingCommand = new DeleteBucketTaggingCommand({ Bucket: BUCKET_NAME_1 }); // 4. 执行命令 try { const response = await s3Client.send(deleteBucketTaggingCommand); this.info += "存储桶标签已成功删除"; this.info += "响应:" this.info += JSON.stringify(response); } catch (error) { if (error.name === "NoSuchBucket") { this.info += "存储桶不存在"; } else if (error.name === "NoSuchBucketTagging") { this.info += "存储桶没有配置标签(无需删除)"; } else { this.info += "删除存储桶标签时出错:" this.info += JSON.stringify(error); } } } ``` 7. PutObjectLockConfigurationCommand 设置 S3 存储桶对象锁定配置 ``` click = async () => { // 3. 定义对象锁定配置 const objectLockConfiguration: ObjectLockConfiguration = { ObjectLockEnabled: "Enabled", // 必须设置为 "Enabled" 才能启用对象锁定 Rule: { DefaultRetention: { Mode: "GOVERNANCE", // 或 "COMPLIANCE" Days: Number("10"), } } }; // 4. 创建 PutObjectLockConfigurationCommand const putObjectLockConfigurationCommand = new PutObjectLockConfigurationCommand({ Bucket: BUCKET_NAME_1, ObjectLockConfiguration: objectLockConfiguration }); // 5. 执行命令 try { const response = await s3Client.send(putObjectLockConfigurationCommand); console.log('PutObjectLockConfigurationCommandBuilder', JSON.stringify(response)); this.info += "存储桶对象锁定配置已成功设置"; this.info += "响应:\n" this.info += JSON.stringify(response); } catch (error) { if (error.name === "NoSuchBucket") { this.info += "存储桶不存在"; } else if (error.name === "InvalidArgument") { this.info += "对象锁定配置无效(如无效的保留策略)"; } else { this.info += "设置存储桶对象锁定配置时出错:\n" this.info += JSON.stringify(error); console.log('PutObjectLockConfigurationCommandBuilder', JSON.stringify(error)); } } } ``` 8. PutObjectRetentionCommand 设置 S3 对象保留策略 ``` click = async () => { // 2. 定义要设置保留策略的对象信息 const bucketName = BUCKET_NAME_1; // 替换为你的存储桶名称 const objectKey = FILE_1; // 替换为你要设置保留策略的对象键 // 3. 定义对象保留策略 const objectRetention: ObjectLockRetention = { Mode: "GOVERNANCE", // 或 "COMPLIANCE" RetainUntilDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) // 30天后保留(ISO 8601 格式) // 或者使用 Years/Months/Days 单位: // RetainUntilDate: { Years: 1, Months: 0, Days: 0 } // 1年后保留 }; // 4. 创建 PutObjectRetentionCommand const putObjectRetentionCommand = new PutObjectRetentionCommand({ Bucket: bucketName, Key: objectKey, Retention: objectRetention }); // 5. 执行命令 try { const response = await s3Client.send(putObjectRetentionCommand); this.info += "对象保留策略已成功设置\n"; this.info += "响应:\n" this.info += JSON.stringify(response); } catch (error) { if (error.name === "NoSuchBucket") { this.info += "存储桶不存在"; } else if (error.name === "NoSuchKey") { this.info += "对象不存在"; } else if (error.name === "InvalidArgument") { this.info += "保留策略无效(如无效的保留日期)"; } else { this.info += "设置对象保留策略时出错:\n" this.info += JSON.stringify(error); } } } ``` ## 接口说明 ### 1. PutObjectCommand 上传对象到S3。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 要上传到的存储桶名称。 | | `Key` | `string` | 是 | 存储对象的键(路径)。 | | `Body` | `Buffer \| ReadableStream \| string` | 是 | 要上传的数据(文件内容)。 | | `ContentType` | `string` | 否 | 对象的MIME类型。 | | `ACL` | `string` | 否 | 应用的预定义ACL(如'private'、'public-read')。 | --- ### 2. GetObjectCommand 从S3下载对象。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 要获取的对象的键。 | --- ### 3. DeleteObjectCommand 从S3删除对象。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 要删除的对象的键。 | --- ### 4. CopyObjectCommand 在S3中复制对象。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 目标存储桶名称。 | | `Key` | `string` | 是 | 目标对象的键。 | | `CopySource` | `string` | 是 | 源对象(格式:`/bucket/key` 或 `bucket/key`)。 | | `MetadataDirective` | `string` | 否 | 是否复制元数据(`COPY` 或 `REPLACE`)。 | --- ### 5. HeadObjectCommand 获取对象的元数据而不下载内容。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 要检查的对象的键。 | --- ### 6. ListObjectsV2Command 列出存储桶中的对象(现代版本)。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Prefix` | `string` | 否 | 仅列出以此前缀开头的对象。 | | `Delimiter` | `string` | 否 | 按公共前缀分组键(用于列出"目录")。 | --- ### 7. ListObjectsCommand (旧版列表对象命令,已不推荐使用) | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Prefix` | `string` | 否 | 仅列出以此前缀开头的对象。 | | `Delimiter` | `string` | 否 | 按公共前缀分组键(用于列出"目录")。 | --- ### 8. RestoreObjectCommand 恢复存档存储中的对象。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 要恢复的对象的键。 | | `RestoreRequest` | `object` | 是 | 包含恢复请求的参数(如天数)。 | --- ### 9. PutObjectAclCommand 设置对象的访问控制列表(ACL)。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 对象的键。 | | `ACL` | `string` | 否 | 要应用的预定义ACL(如'private'、'public-read')。 | --- ### 10. GetObjectAclCommand 获取对象的访问控制列表(ACL)。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 对象的键。 | --- ### 11. PutObjectTaggingCommand 设置对象的标签。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 对象的键。 | | `Tagging` | `object` | 是 | 包含标签的键值对。 | --- ### 12. GetObjectTaggingCommand 获取对象的标签。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 对象的键。 | --- ### 13. DeleteObjectTaggingCommand 删除对象的标签。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 对象的键。 | --- ### 14. PutObjectLegalHoldCommand 设置对象的法律保留。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 对象的键。 | | `LegalHold` | `object` | 是 | 包含法律保留状态的设置。 | --- ### 15. GetObjectLegalHoldCommand 获取对象的法律保留状态。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 对象的键。 | --- ### 16. CreateBucketCommand 创建新的S3存储桶。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 要创建的存储桶名称。 | | `CreateBucketConfiguration` | `object` | 否 | 区域配置(非默认区域时需要)。 | --- ### 17. DeleteBucketCommand 删除S3存储桶。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 要删除的存储桶名称。 | --- ### 18. ListBucketsCommand 列出账户中的所有存储桶。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | (无) | | | 无需参数。 | --- ### 19. GetBucketLocationCommand 获取存储桶所在的区域。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 20. PutBucketAclCommand 设置存储桶的访问控制列表(ACL)。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `ACL` | `string` | 否 | 要应用的预定义ACL(如`private`、`public-read`)。 | --- ### 21. GetBucketAclCommand 获取存储桶的访问控制列表(ACL)。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 22. PutBucketPolicyCommand 设置存储桶策略。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Policy` | `string` | 是 | JSON格式的策略文档。 | --- ### 23. GetBucketPolicyCommand 获取存储桶策略。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 24. DeleteBucketPolicyCommand 删除存储桶策略。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 25. PutBucketCorsCommand 设置存储桶的CORS配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `CORSConfiguration` | `object` | 是 | 包含CORS规则的配置。 | --- ### 26. GetBucketCorsCommand 获取存储桶的CORS配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 27. DeleteBucketCorsCommand 删除存储桶的CORS配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 28. PutBucketLifecycleConfigurationCommand 设置存储桶的生命周期配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `LifecycleConfiguration` | `object` | 是 | 包含生命周期规则的配置。 | --- ### 29. GetBucketLifecycleConfigurationCommand 获取存储桶的生命周期配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 30. DeleteBucketLifecycleCommand 删除存储桶的生命周期配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 31. PutBucketVersioningCommand 启用或禁用存储桶的版本控制。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `VersioningConfiguration` | `object` | 是 | 包含`Status`(`Enabled`或`Suspended`)。 | --- ### 32. GetBucketVersioningCommand 获取存储桶的版本控制状态。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 33. PutBucketWebsiteCommand 设置存储桶的网站配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `WebsiteConfiguration` | `object` | 是 | 包含网站配置的参数。 | --- ### 34. GetBucketWebsiteCommand 获取存储桶的网站配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 35. DeleteBucketWebsiteCommand 删除存储桶的网站配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 36. PutBucketEncryptionCommand 配置存储桶的服务器端加密。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `ServerSideEncryptionConfiguration` | `object` | 是 | 包含加密规则(如SSE-S3、SSE-KMS)。 | --- ### 37. GetBucketEncryptionCommand 获取存储桶的服务器端加密配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 38. DeleteBucketEncryptionCommand 删除存储桶的服务器端加密配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 39. CreateMultipartUploadCommand 初始化分片上传。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 要上传的对象的键。 | | `ContentType` | `string` | 否 | 对象的MIME类型。 | --- ### 40. UploadPartCommand 上传分片上传的一部分。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 对象的键。 | | `UploadId` | `string` | 是 | `CreateMultipartUpload`返回的上传ID。 | | `PartNumber` | `number` | 是 | 分片编号(1-10000)。 | | `Body` | `Buffer \| ReadableStream` | 是 | 此分片的数据。 | --- ### 41. CompleteMultipartUploadCommand 完成分片上传。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 对象的键。 | | `UploadId` | `string` | 是 | 上传ID。 | | `MultipartUpload` | `object` | 是 | 包含分片的ETag和分片编号的列表。 | --- ### 42. AbortMultipartUploadCommand 取消分片上传。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 对象的键。 | | `UploadId` | `string` | 是 | 上传ID。 | --- ### 43. ListMultipartUploadsCommand 列出存储桶中的分片上传。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Prefix` | `string` | 否 | 仅列出以此前缀开头的对象。 | | `Delimiter` | `string` | 否 | 按公共前缀分组键(用于列出"目录")。 | --- ### 44. ListPartsCommand 列出分片上传的部分。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 对象的键。 | | `UploadId` | `string` | 是 | 上传ID。 | --- ### 45. GetBucketLocationCommand (重复项,已在第19项列出) | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 46. PutBucketLoggingCommand 设置存储桶的日志记录配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `LoggingConfiguration` | `object` | 是 | 包含日志记录配置的参数。 | --- ### 47. GetBucketLoggingCommand 获取存储桶的日志记录配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 48. PutBucketNotificationConfigurationCommand 设置存储桶的通知配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `NotificationConfiguration` | `object` | 是 | 包含通知配置的参数。 | --- ### 49. GetBucketNotificationConfigurationCommand 获取存储桶的通知配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 50. PutBucketTaggingCommand 设置存储桶的标签。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Tagging` | `object` | 是 | 包含标签的键值对。 | --- ### 51. GetBucketTaggingCommand 获取存储桶的标签。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 52. DeleteBucketTaggingCommand 删除存储桶的标签。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | --- ### 53. PutObjectLockConfigurationCommand 设置对象锁定配置。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `ObjectLockConfiguration` | `object` | 是 | 包含对象锁定配置的参数。 | --- ### 54. PutObjectRetentionCommand 设置对象保留策略。 | 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | `Bucket` | `string` | 是 | 存储桶名称。 | | `Key` | `string` | 是 | 对象的键。 | | `Retention` | `object` | 是 | 包含保留策略的参数。 | --- 这个文档包含了你列出的所有54个S3操作命令的中文说明,按照你提供的顺序排列,每个命令都包含参数名、类型、必填和说明字段。 ## 关于混淆 - 代码混淆,请查看[代码混淆简介](https://docs.openharmony.cn/pages/v5.0/zh-cn/application-dev/arkts-utils/source-obfuscation.md)。 - 如果希望库在代码混淆过程中不会被混淆,需要在混淆规则配置文件obfuscation-rules.txt中添加相应的排除规则: ``` -keep ./oh_modules/@aws-sdk/client-s3 ``` ## 约束与限制 在下述版本验证通过: - DevEco Studio: 5.0 (5.0.3.500), SDK: API12 (5.0.0.25)。 ## 贡献代码 使用过程中发现任何问题都可以提 [Issue](https://gitcode.com/openharmony-tpc/ohos_mpchart/issues)给组件 ,当然,也非常欢迎发 [PR](https://gitcode.com/openharmony-tpc/ohos_mpchart/pulls)共建 。 ## 开源协议 本项目基于 [Apache License 2.0](https://gitcode.com/openharmony-tpc/ohos_mpchart/blob/master/LICENSE) ,请自由地享受和参与开源。