I use boto3to upload files on Amazon S3 to a django project.
settings.py:
...
AWS_ACCESS_KEY = 'xxxxxxxx'
AWS_SECRET_KEY = 'xxxxxxxx'
S3_BUCKET = 'xxxxx'
REGION_NAME = 'ap-southeast-1'
Template:
<form method=post action="..." enctype=multipart/form-data>
{% csrf_token %}
<input type="file" name="fileToUpload">
<input type=submit value=Upload>
</form>
View:
from mysite.settings import AWS_ACCESS_KEY, AWS_SECRET_KEY, S3_BUCKET, REGION_NAME
import boto3
from boto3.session import Session
fileToUpload = request.FILES.get('fileToUpload')
session = Session(aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY,
region_name=REGION_NAME)
s3 = session.resource('s3')
fpath = os.path.dirname(os.path.realpath(__file__)) + '/abc.png'
f = open(fpath, 'rb')
s3.Bucket(S3_BUCKET).put_object(Key='uploads/test2.png', Body=f)
For an existing file, abc.pngit loads into Amazon S3 correctly. However, how can I upload a user-selected file fileToUploadinstead of an existing file abc.png?
source
share