Flask / Flask File Uploads and Media Handling
Uploading Files and Images in Flask
This tutorial will guide you on how to build a simple Flask application that allows users to upload files and images.
Section overview
5 resourcesExplains how to handle file uploads and manage media files in Flask.
1. Introduction
In this tutorial, our goal is to guide you on how to build a simple Flask application that allows users to upload files and images. Flask is a web framework for Python, which is a great tool for web development.
You will learn:
- How to create a Flask application
- How to handle file uploading in Flask
- How to display uploaded images in Flask
Prerequisites: Basic knowledge of Python and HTML
2. Step-by-Step Guide
The first step is to install Flask using pip:
pip install flask
File Uploading in Flask
Flask makes it easy to upload files via the request.files object. The file will be stored in a temporary location on the server, and then you can save it to a directory of your choice.
Displaying Uploaded Images in Flask
After the image is uploaded, you can display it using the url_for() function, which generates a URL for a given route.
3. Code Examples
Let's create a Flask application that accepts file uploads.
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
app = Flask(__name__)
@app.route('/upload', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
# secure the file name and save it
f.save(secure_filename(f.filename))
return 'file uploaded successfully'
if __name__ == '__main__':
app.run(debug = True)
In this code:
- We import the necessary modules from flask and werkzeug.
- We create a route '/upload' that accepts POST requests.
- If the request method is POST, we get the file from the request.
- We secure the filename with secure_filename() and save it.
- If the file is uploaded successfully, we return a success message.
To upload a file, you can use a simple HTML form. Here's an example:
<html>
<body>
<form action = "http://localhost:5000/upload" method = "POST"
enctype = "multipart/form-data">
<input type = "file" name = "file" />
<input type = "submit"/>
</form>
</body>
</html>
4. Summary
In this tutorial, we covered how to create a simple Flask application that handles file uploads. We learned how to use the request.files object to access uploaded files, and how to use the secure_filename() function to secure file names.
For further learning, you could explore how to limit the file types and sizes that can be uploaded, or how to handle multiple file uploads.
5. Practice Exercises
- Modify the Flask application to accept and display uploaded images.
- Add validation to only accept files of a certain type (e.g., .jpg and .png files).
- Allow the user to upload multiple files at once.
Here's a solution for exercise 1:
from flask import Flask, render_template, request, url_for
from werkzeug.utils import secure_filename
app = Flask(__name__)
@app.route('/upload', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
filename = secure_filename(f.filename)
f.save(filename)
return '<img src='+ url_for('static', filename=filename) +'>'
if __name__ == '__main__':
app.run(debug = True)
In this code, after saving the file, we return an HTML string that contains an <img> tag. The src attribute of the <img> tag is the URL of the uploaded image, which we generate with the url_for() function. We pass 'static' as the endpoint and the filename as a keyword argument. This assumes that you're saving the uploaded images in the 'static' directory of your Flask application.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article