首页 > 解决方案 > 使用 Python boto3 在 AWS 中上传图像

问题描述

我尝试在 AWS s3-Bucket 中上传图像,我正在使用 boto3 并且可以正常工作,但是当我打开链接时,它会自动下载图像,并且当我手动上传图像时会在 web-browser 中打开。什么是问题?

这是我的代码。

import boto3
from botocore.exceptions import NoCredentialsError

ACCESS_KEY = 'xxxxxxxxxxxxxxxxx'
SECRET_KEY = 'xxxxxxxxxxxxxxxxx+4Tr4nUp'

def upload_to_aws(local_file, bucket, s3_file):
    s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY,
                      aws_secret_access_key=SECRET_KEY)

    try:
        s3.upload_file(local_file, bucket, s3_file)
        print("Upload Successful")
        return True
    except FileNotFoundError:
        print("The file was not found")
        return False
    except NoCredentialsError:
        print("Credentials not available")
        return False


uploaded = upload_to_aws('test.jpg', 'testverifcation', 'test.jpg')

标签: python-3.xamazon-web-servicesamazon-s3amazon-ec2boto3

解决方案


try:
    s3.upload_file(local_file, bucket, s3_file,ExtraArgs={'ACL': 'public-read', 'ContentType': 'image'})
    print("Upload Successful")
    return True
except FileNotFoundError:
    print("The file was not found")
    return False
except NoCredentialsError:
    print("Credentials not available")
    return False

推荐阅读