Uploading a file from HTML form with Flask and Boto3 Uploading a file from HTML form with Flask and Boto3 flask flask

Uploading a file from HTML form with Flask and Boto3


Once you get the uploaded file from the Flask request you can upload it using the conn.upload_fileobj() method. You are now using conn.upload_file() which expects a filename that points to a file on disk.

Do something like

file = request.files['filefield']conn.upload_fileobj(file, 'mybucket', 'mykey')

More documentation and information:

The Flask request object gives you a FileStorage object behaves like a regular Python file: http://flask.pocoo.org/docs/0.12/api/#flask.Request.files

Read up on the Boto3 documentation here: https://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.upload_fileobj


You need to build a form with a signed policy as documented here:https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html

You can use this Flask utility to do the signature generation for you:https://github.com/fastmonkeys/pontus

Copy-pasting from the example on their website, to generate the form field values:(it's up to you to put that in an HTML form):

import boto3from flask import current_appfrom pontus import AmazonS3SignedRequestsession = boto3.session.Session(    aws_access_key_id=current_app.config.get('AWS_ACCESS_KEY_ID'),    aws_secret_access_key=current_app.config.get('AWS_SECRET_ACCESS_KEY'))bucket = session.resource('s3').Bucket('testbucket')signed_request = AmazonS3SignedRequest(    key_name=u'my/file.jpg',    mime_type=u'image/jpeg',    bucket=bucket,    session=session)signed_request.form_fields