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')