| 1 | import os |
| 2 | from flask import Flask, flash, request, redirect, url_for |
| 3 | from werkzeug.utils import secure_filename |
| 4 | |
| 5 | UPLOAD_FOLDER = "/tmp/" |
| 6 | ALLOWED_EXTENSIONS = {"txt", "pdf", "png", "jpg", "jpeg", "gif"} |
| 7 | |
| 8 | app = Flask(__name__) |
| 9 | app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER |
| 10 | |
| 11 | |
| 12 | def allowed_file(filename): |
| 13 | return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS |
| 14 | |
| 15 | |
| 16 | @app.route("/", methods=["GET", "POST"]) |
| 17 | def upload_file(): |
| 18 | if request.method == "POST": |
| 19 | # check if the post request has the file part |
| 20 | if "file" not in request.files: |
| 21 | return redirect(request.url) |
| 22 | file = request.files["file"] |
| 23 | # if user does not select file, browser also |
| 24 | # submit an empty part without filename |
| 25 | if file.filename == "": |
| 26 | return redirect(request.url) |
| 27 | if file and allowed_file(file.filename): |
| 28 | filename = secure_filename(file.filename) |
| 29 | file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename)) |
| 30 | return redirect(url_for("uploaded_file", filename=filename)) |
| 31 | |
| 32 | return """ |
| 33 | <!doctype html> |
| 34 | <title>Upload new File</title> |
| 35 | <h1>Upload new File</h1> |
| 36 | <form method=post enctype=multipart/form-data> |
| 37 | <input type=file name=file> |
| 38 | <input type=submit value=Upload> |
| 39 | </form> |
| 40 | """ |