Created
February 26, 2021 18:05
-
-
Save angeloped/90f9edee6981b7fdbb343e7963185673 to your computer and use it in GitHub Desktop.
Upload file with Flask microframework.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from flask import Flask, flash, request, redirect, url_for | |
from werkzeug.utils import secure_filename | |
if not os.path.exists("uploads/"): | |
os.mkdir("uploads") | |
UPLOAD_FOLDER = 'uploads/' | |
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 user does not select file, browser also | |
# submit 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) | |
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) | |
return redirect(request.url) | |
return ''' | |
<!doctype htm | |
<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> | |
''' | |
if __name__ == '__main__': | |
app.run(debug = True) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment