django boto3: save uploaded file on Amazon S3 -


i using boto3 upload files amazon s3 in 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 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 existing file abc.png, uploaded amazon s3 correctly. however, how upload user-selected file filetoupload instead of existing file abc.png?

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

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -