Hey guys! Welcome back, in this video I will be showing you how to upload files using Python and Flask. We're going to use Flask to build our website, Flask_WTF, and WTForms to create our forms and Werkzeug to securely save our files. There are links down below for the code and the official Flask documentation.

If you don't know about Flask, Flask is a Python web framework that is lightweight and easy to use. It is a good choice for beginners, and it can be used to create web applications that are scalable. Flask can be used with WTForms to create forms on pages and these forms can be used to upload files as well.

Source Code:

from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import FileField, SubmitField
from werkzeug.utils import secure_filename
import os
from wtforms.validators import InputRequired

app = Flask(__name__)
app.config['SECRET_KEY'] = 'supersecretkey'
app.config['UPLOAD_FOLDER'] = 'static/files'

class UploadFileForm(FlaskForm):
    file = FileField("File", validators=[InputRequired()])
    submit = SubmitField("Upload File")

@app.route('/', methods=['GET',"POST"])
@app.route('/home', methods=['GET',"POST"])
def home():
    form = UploadFileForm()
    if form.validate_on_submit():
        file = form.file.data # First grab the file
        file.save(os.path.join(os.path.abspath(os.path.dirname(__file__)),app.config['UPLOAD_FOLDER'],secure_filename(file.filename))) # Then save the file
        return "File has been uploaded."
    return render_template('index.html', form=form)

if __name__ == '__main__':

Code Repo: https://github.com/arpanneupane19/Flask-File-Uploads
Official Flask Documentation: https://flask.palletsprojects.com/en/2.0.x/

Subscribe: https://www.youtube.com/@ArpanNeupaneProductions/featured 

#python #flask 

Upload Files with Flask Using Python
1.65 GEEK