File Upload in Python Flask

The following example shows, how to upload a file in Python Flask.

File Structure:

File Upload in Python Flask
  • Create the 'files' folder inside of 'static' folder for file uploading.

from flask import Flask,render_template,request,redirect,flash
from werkzeug.utils import secure_filename
import os
import random

UPLOAD_FOLDER ="static/files"
FILE_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__)

#check file extension
def allowed_extensions(file_name):
    return '.' in file_name and file_name.rsplit('.',1)[1].lower() in FILE_EXTENSIONS
#file Upload
def fileUpload():
    if request.method=='POST':
        if 'file' not in request.files:
            flash('No file part','danger')
        file = request.files['file']
        if file.filename == '':
            flash('No file selected','danger')
        if file and allowed_extensions(file.filename):
            filename, file_extension = os.path.splitext(file.filename)
            new_filename = secure_filename(filename+str(random.randint(10000,99999))+"."+file_extension)
  , new_filename))   
            flash(file.filename+' Uploaded Successfully','success')
    return render_template('fileUpload.html')
if __name__=='__main__':


    <title>File Upload in Flask</title>
    <!-- Flash Message -->
    {% with messages = get_flashed_messages(with_categories=true) %}
      {% if messages %}
        {% for category, message in messages %}
        <h3 class='{{category}}'>{{ message }}</h3>
        {% endfor %}
      {% endif %}
    {% endwith %}
    <h3>File Upload</h3>
    <form method='post' action='/fileUpload' enctype='multipart/form-data'>
      <p><input type='file'  name='file'></p>
      <p><input type='submit' value='Submit'></p>

Run the Project:

  1. Run '' file.
  2. Browse the URL 'localhost:5000/fileUpload'


Flask MySql Login and Registration With Session