AWS SDK FOR JavaScript V2 操作对象相关的API

本文介绍的主要是 V2 版本相关的API去操作对象,V2和V3有些区别,但是大部分的API用法基本一致,需要添加自定义请求头可以参照【listObjects】

一. 初始化相关的参数

import { ObjectCannedACL } from '@aws-sdk/client-s3'
import AWS, { AWSError, S3 } from 'aws-sdk'

const s3 = new AWS.S3({
  apiVersion: '2006-03-01', // 这个随便填
  endpoint: 'http://x.x.x.x:8080', // 可以填写对应的endpoint地址
  accessKeyId: 'xxxxx', // ak     aksk是对应的身份信息
  secretAccessKey: 'xxxxx', // sk
  s3ForcePathStyle: true,
  // region: "xxx", // 区域
})

二. 相关API的使用

2.1 获取存储桶中所有的对象

/**
 *
 * @param bucket_name 桶名称
 * @param prefix 搜索的关键字,或者是进入目录请求的前缀
 * @param nextKey 下一页的key,如果没有下一页了就会返回 ''
 * @param limit 每页限制多少条
 */
// 列出存储桶中的所有对象
function getObjectListV2Fn(
  bucket_name = '',
  prefix = '',
  nextKey = '',
  limit = 10,
  callback = (err: AWSError, data: S3.Types.ListObjectsOutput) => {},
) {
  const req = s3.listObjects({
    Bucket: bucket_name,
    MaxKeys: limit,
    Delimiter: '/', // 区分目录和普通对象
    Marker: nextKey,
    Prefix: prefix,
  })
  // 添加自定义请求头
  req.on('build', () => {
    req.httpRequest.headers['Request-From'] = 'web'
  })

  req.send(callback)
  // 返回示例
  // {
  //   Delimiter: "/",
  //   IsTruncated: true, // 是否存在下一页
  //   Marker: "",
  //   MaxKeys: 10,
  //   Name: "xxx", // 桶名
  //   NextMarker: "1LZ4WtQ76OyxVqRodX-pE",
  //   Prefix: "",
  //   Contents: [
  //     {
  //       ChecksumAlgorithm: [],
  //       ETag: "\"xxx\"",
  //       Key: "xxx",
  //       LastModified: 'Tue Jun 20 2023 17:41:04 GMT+0800 (中国标准时间) {}',
  //       Owner: {DisplayName: 'xxx', ID: 'xxx'},
  //       Size: 4096,
  //       StorageClass: "STANDARD", // 对象的类型
  //     }
  //   ],
  //   CommonPrefixes: [{Prefix: '01/'}]
  // }
}

2.2 获取对象的下载链接

/**
 * @param {bucket_name: string} 对象所在的桶名
 * @param {key: string} 对象所在桶中的路径
 * @returns {url: string} 下载的链接
 */
async function downloadObjectURLV2Fn(bucket_name: string, key: string, expires?: number) {
  const params = {
    Bucket: bucket_name,
    Key: key,
    Expires: expires, // 有效期(秒)
  }

  const url = await s3.getSignedUrl('getObject', params)
  console.log(`下载链接V2版本--getObject: ${url}`)
  return url
}

2.3 创建目录

/**
 * 创建目录 S3 中的目录只是一个没有内容的对象,其 key 以斜杠结尾表示。
 * 这个会在目录下自动创建一个同名的文件,展示时需要把这个文件过滤一下
 * @param bucket_name 桶名
 * @param dir_name 目录名称
 * @param callback 创建成功会返回一个 {} 空对象
 */
async function createDirectoryV2Fn(
  bucket_name = '',
  dir_name = '',
  StorageClass = 'STANDARD',
  callback?: (err: AWSError, data: S3.Types.PutObjectOutput) => void,
) {
  // 使用 putObject 方法创建一个空的目录对象
  const req = await s3.putObject({
    Bucket: bucket_name,
    Key: dir_name,
    StorageClass,
    Body: '',
  })
  req.send(callback)
}

2.4 删除单个对象

/**
 * 删除单个对象
 * @param bucket_name 桶名
 * @param key 需要删除的对象的key值
 * @param callback 返回值
 */
async function deleteObjectV2Fn(
  bucket_name: string,
  key: string,
  callback: (err: AWSError, data: S3.Types.DeleteObjectOutput) => void,
) {
  const req = await s3.deleteObject({
    Bucket: bucket_name,
    Key: key,
  })
  req.send(callback)
}

2.5 批量删除对象

/**
 * 删除多个对象
 * @param bucket_name 桶名
 * @param keys 需要删除对象的Key的集合
 * @param callback 返回出对应的删除结果
 */
async function deleteObjectsV2Fn(
  bucket_name: string,
  keys: { Key: string }[],
  callback: (err: AWSError, data: S3.Types.DeleteObjectsOutput) => void,
) {
  // const deleteParams = {
  //   Bucket: 'your-bucket-name',
  //   Delete: {
  //     Objects: [{ Key: 'key-1' }, { Key: 'key-2' }, { Key: 'key-3' }],
  //     Quiet: false,
  //   },
  // }

  // 返回示例
  // {
  //   Deleted: [
  //     {Key: '001'},
  //     {Key: '001.jpg'},
  //     {Key: '001.png'},
  //   ],
  //   Errors: [
  //     {
  //       Code: "404",
  //       Key: "0001110001",
  //       Message: "NoSuchKey",
  //       VersionId: "",
  //     }
  //   ]
  // }

  /**
   * 在安静模式下,如果请求成功,则不会返回任何响应信息;如果请求失败,则会返回一个错误响应。Quiet: true
   * 该对象包含有关删除操作的信息,如哪些对象已成功删除、哪些对象由于某种原因未能删除以及任何错误消息。Quiet: false,
   */
  const req = await s3.deleteObjects({
    Bucket: bucket_name,
    Delete: {
      Objects: keys,
      Quiet: false,
    },
  })

  req.send(callback)
}

2.6 单个复制对象

/**
 * 单个复制对象
 * @param new_bucket_name 目标桶
 * @param new_path 目标路径
 * @param source_path 源路径 ==> 原桶 + 路径
 * @param callback 返回值
 */
async function copyObjectV2Fn(
  new_bucket_name: string,
  new_path: string,
  source_path: string,
  callback: (err: AWSError, data: S3.Types.CopyObjectOutput) => void,
) {
  // const copyParams = {
  //   Bucket: 'your-bucket-name', // 目标桶
  //   CopySource: '/source-bucket-name/source-object-key', // 源桶 + 路径
  //   Key: 'your-new-object-key', // 目标路径
  // }


  const req = await s3.copyObject({
    Bucket: new_bucket_name,
    CopySource: source_path,
    Key: new_path,
  })


  req.send(callback)
}

2.7 获取文件ACL

// 获取文件acl
async function getObjectACLV2Fn(
  bucket_name: string,
  key: string,
  callback: (err: AWSError, data: S3.Types.GetObjectAclOutput) => void,
) {
  const req = await s3.getObjectAcl({
    Bucket: bucket_name,
    Key: key,
  })

  req.send((err, data) => {
    console.log(err, data, '获取文件的acl')
  })
  // "FULL_CONTROL" 私有
  // "READ"、 "WRITE"、"FULL_CONTROL" 公共读写
  // "READ"、"FULL_CONTROL" 公共读

// 返回示例
//   {Grants : [
//     {
//       Grantee: {Type: 'Group', URI: 'xxx'},
//       Permission: "READ"
//     },
//     {
//       Grantee: {DisplayName: 'xxx', ID: 'xxx', Type: 'CanonicalUser'},
//       Permission: "FULL_CONTROL"
//     }
//   ],
//  Owner: {DisplayName: "xxx", ID: "xxx"}
//  }
}

2.8 更新文件 ACL

// 更新文件的acl
async function putObjectACLV2Fn(
  bucket_name: string,
  key: string,
  acl: ObjectCannedACL,
  callback: (err: AWSError, data: S3.Types.PutObjectAclOutput) => void,
) {
  // export type ObjectCannedACL = "private"|"public-read"|"public-read-write"|"authenticated-read"|"aws-exec-read"|"bucket-owner-read"|"bucket-owner-full-control"|string;
  const req = await s3.putObjectAcl({
    ACL: acl,
    Bucket: bucket_name,
    Key: key,
  })

  req.send((err, data) => {
    console.log(err, data, '更新文件的acl')
  })
}

2.9 解冻

// 获取对象的解冻状态
async function getObjectRestoreV2Fn(
  Bucket: string,
  Key: string,
  callback: (err: AWSError, data: S3.Types.RestoreObjectOutput) => void,
) {
  const req = await s3.restoreObject({
    Bucket,
    Key,
    // RestoreRequest: {
    //   Days: 1,
    // },
  })

  req.send(callback)
}

2.10 获取对象的信息但是一个会获取不全

// 根据具体需要,获取到对应的详情可能需要调用两个API getObject 和 headObject
/**
 * @param bucket_name 桶名
 * @param key 对象所在的路径
 * @param callback 返回值通过回调函数返回出去
 */
// 获取桶中得对象
async function getObjectV2Fn(
  bucket_name: string,
  key: string,
  callback: (err: AWSError, data: S3.Types.GetObjectOutput) => void,
) {
  const req = await s3.getObject({
    Bucket: bucket_name,
    Key: key,
  })

  req.send(callback)
}

// 访问object的属性
async function headObjectV2Fn(
  bucket: string,
  key: string,
  callback: (err: AWSError, data: S3.Types.HeadObjectOutput) => void,
) {
  const req = await s3.headObject({
    Bucket: bucket,
    Key: key,
  })

  req.send(callback)
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值