Skip to content

Instantly share code, notes, and snippets.

Last active May 7, 2018 02:38
Show Gist options
  • Save thijstriemstra/81bdfe06cc4635c2c1220bf3a4b4a0a4 to your computer and use it in GitHub Desktop.
Save thijstriemstra/81bdfe06cc4635c2c1220bf3a4b4a0a4 to your computer and use it in GitHub Desktop.
example upload Flask server
import os
from flask import Flask, flash, request, redirect, url_for, render_template, send_from_directory
from werkzeug import secure_filename
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = set(['webm', 'mp4', 'mp3', 'wav', 'jpeg', 'gif', 'png'])
static_folder = os.path.abspath(os.path.dirname(__file__))
template_dir = os.path.join(static_folder, 'examples')
app = Flask(__name__, template_folder=template_dir)
app.secret_key = 'super secret key'
# limit size for uploaded files to 16 MB max
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# Custom static data
def node_modules(filename):
return send_from_directory(os.path.join(static_folder, 'node_modules'), filename)
def dist(filename):
return send_from_directory(os.path.join(static_folder, 'dist'), filename)
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
print('saving uploaded file..')
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
print('filename: {}'.format(file.filename))
# if user does not select file, browser also
# submits an empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)['UPLOAD_FOLDER'], filename))
print('saved uploaded file.')
return redirect(url_for('uploaded_file',
return render_template('upload/simple.html')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment