云存储实战:对接 AWS S3 实现文件上传与下载

本文将逐步指导您使用 Python 的 Boto3 库实现 AWS S3 的文件上传与下载功能。所有操作均需配置 AWS 访问凭证(Access Key 和 Secret Key)。


1. 环境准备
  1. 安装必要库:
    pip install boto3
    

  2. 配置 AWS 凭证:
    • ~/.aws/credentials 添加:
      [default]
      aws_access_key_id = YOUR_ACCESS_KEY
      aws_secret_access_key = YOUR_SECRET_KEY
      

    • ~/.aws/config 添加:
      [default]
      region = us-east-1  # 替换为您的区域
      


2. 创建 S3 存储桶
import boto3

s3 = boto3.client('s3')

def create_bucket(bucket_name):
    try:
        s3.create_bucket(Bucket=bucket_name)
        print(f"存储桶 {bucket_name} 创建成功")
    except Exception as e:
        print(f"创建失败: {e}")

# 调用示例
create_bucket("my-demo-bucket-123")

⚠️ 存储桶名称需全球唯一,建议添加随机后缀


3. 文件上传实现
def upload_file(bucket_name, file_path, object_name=None):
    if object_name is None:
        object_name = file_path.split("/")[-1]  # 默认使用文件名
    
    try:
        s3.upload_file(file_path, bucket_name, object_name)
        print(f"文件 {object_name} 上传成功")
    except Exception as e:
        print(f"上传失败: {e}")

# 调用示例
upload_file("my-demo-bucket-123", "local/test.jpg", "images/test.jpg")


4. 文件下载实现
def download_file(bucket_name, object_name, download_path):
    try:
        s3.download_file(bucket_name, object_name, download_path)
        print(f"文件 {object_name} 下载到 {download_path}")
    except Exception as e:
        print(f"下载失败: {e}")

# 调用示例
download_file("my-demo-bucket-123", "images/test.jpg", "local/downloaded.jpg")


5. 高级功能
  1. 生成预签名 URL(限时下载链接)

    def generate_presigned_url(bucket_name, object_name, expiration=3600):
        url = s3.generate_presigned_url(
            'get_object',
            Params={'Bucket': bucket_name, 'Key': object_name},
            ExpiresIn=expiration
        )
        print(f"预签名URL(有效期 {expiration}秒): {url}")
        return url
    
    # 调用示例
    generate_presigned_url("my-demo-bucket-123", "images/test.jpg")
    

  2. 列出存储桶文件

    def list_bucket_files(bucket_name):
        response = s3.list_objects_v2(Bucket=bucket_name)
        for obj in response.get('Contents', []):
            print(f"文件: {obj['Key']}, 大小: {obj['Size']}字节")
    
    # 调用示例
    list_bucket_files("my-demo-bucket-123")
    


6. 安全注意事项
  1. 权限控制
    • 通过 IAM 策略限制用户权限,例如:
      {
          "Version": "2012-10-17",
          "Statement": [{
              "Effect": "Allow",
              "Action": ["s3:PutObject", "s3:GetObject"],
              "Resource": "arn:aws:s3:::my-demo-bucket-123/*"
          }]
      }
      

  2. 数据传输加密
    • 上传时启用加密:
      s3.upload_file(file_path, bucket_name, object_name, 
                    ExtraArgs={'ServerSideEncryption': 'AES256'})
      

  3. 敏感凭证管理
    • 避免在代码中硬编码凭证,使用环境变量或 AWS Secrets Manager

通过上述步骤,您已实现完整的 S3 文件上传下载功能。建议结合 AWS CloudWatch 监控 API 调用日志,确保操作安全可靠。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐