boto3上傳下載文件

肯定文件類型,此處使用內置filetype模塊

import filetype
file_type = filetype.guess_extension(file.read())

生成惟一key用於標示上傳或下載的文件,key只要是惟一便可

建立client

def create_aws_client():
   # 這裏換成你aws服務器的相關配置 access_key
= settings.AWS_ACCESS_KEY secret_key = settings.AWS_SECRET_KEY region = settings.AWS_REGION client = boto3.client( 's3', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name=region ) return client

上傳

def upload_fileobj(file, key):
  # 更換你的bucketname,path是你aws服務器上存儲文件的目錄 bucket
= settings.BUCKET client = create_aws_client() client.upload_fileobj(file, bucket, path + key)

下載

def get_file_by_key(key):
    bucket = settings.BUCKET
    client = create_aws_client()
    try:
        resp = client.get_object(
            Bucket=bucket,
            Key=key
        )
    except client.exceptions.NoSuchKey:
        return None

    return resp.get('Body')
相關文章
相關標籤/搜索