import boto3
import mimetypes

def fix_content_type_by_key(bucket_name, object_key):
	  """
	  	已上传至s3无ContentType文件,需要替换为指定ContentType文件
        bucket_name:桶名
        object_key:文件在桶中路径
        AWS_ACCESS_KEY_ID: aws认证id
        AWS_SECRET_ACCESS_KEY: aws认证key
    """
    # 自动判断文件content type类型
    content_type, _ = mimetypes.guess_type(object_key)
    print(content_type)
		# 建立s3连接
    s3_client = boto3.resource(
        's3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY
    )
    # 建立s3对象,新文件存储位置。
    obj = s3_client.Object(bucket_name, object_key)

    try:
    			# 源文件来源
        copy_source = {'Bucket': bucket_name, 'Key': object_key}
        # 将源文件复制到新文件存储位置
        obj.copy_from(
            CopySource=copy_source,
            # REPLACE是新元数据替换原元数据
            MetadataDirective='REPLACE',
            # 告知s3文件类型
            ContentType=content_type
        )
        print("update {} -> Content-Type: {}".format(object_key, content_type))
        return True
    except Exception as e:
        print("no update {}: {}".format(object_key, e))
        return False

首次上传文件制定ContentType

	mime_type, _ = mimetypes.guess_type(image.name)
  s3 = boto3.resource(
    's3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY
  )
  s3.Object(AWS桶名, 文件上传桶中位置).upload_fileobj(
    上传的文件, ExtraArgs={'ContentType': mime_type}
  )

更多推荐