Flask is a lightweight web framework that helps you build web apps easily. In this article, we’ll make a simple Flask app that lets you upload files to the server
Start by creating a new folder. Then, inside that folder, create and activate a virtual environment.
mkdir flask_app && cd flask_app
python -m venv .venv && source .venv/bin/activate
Install Flask using pip.
pip install flask
Let your project follow the structure below.
flask_upload/
|-- uploads/
|-- templates/
| |-- upload.html
|-- app.py
In app.py
, import Flask and set up the upload
function along with its route.
from flask import Flask, request
from flask import render_template
app = Flask(__name__)
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
file = request.files['file']
file.save(f'uploads/{file.filename}')
return render_template('upload.html')
The upload
function will check for a POST request. If it finds one, it will get the file from the request.files
dictionary and save it using the file’s save method.
The HTML code for upload.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Upload File</title>
</head>
<body>
<h1>Upload File</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<button type="submit">Upload</button>
</form>
</body>
</html>
Video resource based on this article.
Uploading files with Flask is straightforward, as I’ve shown. Flask is easy to understand and a great choice for your side projects.