Welcome to the Files Upload tutorial using Flask! In this lesson, you will learn how to handle file uploads in your Flask applications. This skill is essential when building dynamic websites that require user-generated content.
Before diving into the code, let's discuss the request.files module in Flask that we'll be using for handling file uploads. š” Remember, request is a built-in object in Flask that contains information about the HTTP request.
request.files is a dictionary-like object that enables access to uploaded files in a Flask application. It allows you to work with files directly, saving them to a local directory, moving them, or even processing them on the fly.
To get started, ensure you have Flask installed on your machine. If you haven't installed it yet, you can do so by running:
pip install flaskNow, let's create a simple Flask application with a file upload form.
Create a new folder for your Flask project, and navigate to it in your terminal.
mkdir flask-file-upload
cd flask-file-uploadCreate a new Python file called app.py:
touch app.pyOpen app.py and add the following code:
from flask import Flask, render_template, request
from os import path
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
if not path.exists(app.config['UPLOAD_FOLDER']):
path.mkdir(app.config['UPLOAD_FOLDER'])
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file:
filename = file.filename
file.save(path.join(app.config['UPLOAD_FOLDER'], filename))
return f'File {filename} uploaded successfully!'
return render_template('upload_form.html')
@app.route('/success')
def success():
return 'File has been uploaded successfully!'
if __name__ == '__main__':
app.run(debug=True)Now, let's create an HTML file for our file upload form.
Create a new folder called templates, and inside it, create a new HTML file called upload_form.html:
mkdir templates
touch templates/upload_form.htmlAdd the following code to upload_form.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload Form</title>
</head>
<body>
<h1>Upload a file</h1>
<form action="/" method="POST" enctype="multipart/form-data">
<input type="file" name="file" accept=".txt, .pdf, .jpg">
<button type="submit">Upload</button>
</form>
</body>
</html>In your terminal, run the following command:
python app.pyNow, open your browser and navigate to http://127.0.0.1:5000/. You should see a simple file upload form. Upload a file, and you'll see a success message!
š Note: The app.config['UPLOAD_FOLDER'] is the directory where uploaded files will be saved.
To handle multiple files at once, modify the upload_file function in app.py as follows:
if request.method == 'POST':
files = request.files.getlist('file[]')
for file in files:
filename = file.filename
file.save(path.join(app.config['UPLOAD_FOLDER'], filename))
return f'Files uploaded successfully!'With this change, the upload_file function can now handle multiple files at once.
In a real-world scenario, you can use this feature to allow users to upload images, documents, or other files to your Flask application, making it more interactive and engaging!
What is the purpose of the request.files module in Flask?