Skip to content

Instantly share code, notes, and snippets.

@m-ocean-it
Last active May 18, 2021 07:46
Show Gist options
  • Save m-ocean-it/dabf0d58f1494496be3a1a0acd49e301 to your computer and use it in GitHub Desktop.
Save m-ocean-it/dabf0d58f1494496be3a1a0acd49e301 to your computer and use it in GitHub Desktop.
Upload files to a web server using Flask
import os
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = 'path/to/upload/folder'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_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']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(request.url)
return render_template('upload_page.html')
app.run()
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
@m-ocean-it
Copy link
Author

Tiny change from the official example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment