Skip to content

Instantly share code, notes, and snippets.

@seanbehan
Last active June 4, 2018 21:08
Show Gist options
  • Save seanbehan/73e947f754f9ed7feff0e6d7bf836f2a to your computer and use it in GitHub Desktop.
Save seanbehan/73e947f754f9ed7feff0e6d7bf836f2a to your computer and use it in GitHub Desktop.
upload files to s3 with flask, PIL and tinys3

HTML form for file uploads

<!-- in templates/form.html -->
<form action="/upload" method="POST" enctype="multipart/form-data">
 <input type="file" name="logo">
 <button>Upload</button>
</form>

Libs and routes for handling file uploads

from flask import Flask, request, redirect, render_template as render
from uuid import uuid4
import tinys3
from werkzeug import secure_filename
from PIL import Image

s3 = tinys3.Connection(AWS_KEY, AWS_SECRET, tls=True)

app = Flask(__name__)

@app.route("/")
def index():
   return render('form.html')

@app.route("/upload", methods=["POST"])
def upload():
    if request.files.has_key('logo') and request.files['logo']:
        file = request.files['logo']
        base_file_name = "%s-%s" % (str(uuid4()), secure_filename(file.filename))
        file_name = 'tmp/%s' % base_file_name
        file.save(file_name)
        img = Image.open(file_name)
        img2 = img.crop((0,0,200,200))
        img2.save(file_name)

        resp = s3.upload(base_file_name, open(file_name))
        return redirect(resp.url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment