Flask allows you to handle file uploads from users in your web applications. This is useful for tasks like uploading images, documents, and other files. In this guide, we'll explore how to handle file uploads in Flask, including creating an HTML form for uploads and writing Python code to process the uploaded files.
Step 1: Create an HTML Form for File Upload
Create an HTML form that allows users to select and upload files. Here's an example of an HTML form:
<title>File Upload Form</title>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload File">
The `enctype="multipart/form-data"` attribute is essential for file uploads.
Step 2: Process File Uploads in Flask
In your Flask application, create a route that handles file uploads. Use the `request.files` object to access the uploaded file. Here's an example of a Flask route for file uploads:
from flask import Flask, request, render_template
app = Flask(__name)
if 'file' not in request.files:
return 'No file part' file = request.files['file'] if file.filename == '':
return 'No selected file' if file:
# You can process and save the file here
# For example, save it to the 'uploads' folder
file.save('uploads/' + file.filename)
return 'File uploaded successfully'
return 'Upload failed'
if __name__ == '__main__':
The uploaded file is accessed using `request.files['file']`, and you can process and save it as needed.
Step 3: Display Success or Error Messages
You can enhance user experience by displaying success or error messages. For example, you can redirect to a new page or display a message after processing the uploaded file.
Handling file uploads in Flask is a crucial feature for web applications that require users to upload files. By following these steps, you can create a file upload form, process uploaded files, and enhance the user experience by displaying success or error messages. You can further expand on this foundation to build more complex file upload systems in your Flask applications.