I am using boto3
to upload files to Amazon S3 in 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 the existing file abc.png
, it is uploaded to Amazon S3 correctly. However, how do I upload the user-selected file fileToUpload
instead of the existing file abc.png
?
Building a simple Django Rest API application Execute the commands below to set up the project. Add the code snippet below to urls.py file in the dropboxer project directory. Create serializers.py and urls.py files in the uploader app. In models.py file, we create a simple model that represents a single file.
The following does the job:
def upload(request):
if request.method=='GET':
return render(request, '<someTemplate>')
# POST
fileToUpload = request.FILES.get('fileToUpload')
cloudFilename = '<someDirectory>/' + fileToUpload.name
session = boto3.session.Session(aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY)
s3 = session.resource('s3')
s3.Bucket(AWS_BUCKET_NAME).put_object(Key=cloudFilename, Body=fileToUpload)
return redirect('<destinationTemplate>')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With