Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django boto3: save uploaded file on Amazon S3

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?

like image 324
Randy Tang Avatar asked Jul 07 '15 17:07

Randy Tang


People also ask

How do I upload files to AWS S3 using Django REST framework?

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.


1 Answers

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>')
like image 87
Randy Tang Avatar answered Sep 29 '22 16:09

Randy Tang