Introduction

Uploading images is a common feature in web applications, and Flask makes it straightforward to implement. In this guide, we'll explore how to upload images in Flask, store them on the server, and display them on web pages. By following this guide, you'll be able to enhance your web applications with image upload functionality.


Step 1: Setting Up Your Flask Application

Start by setting up your Flask application and installing the necessary extensions. Here's a sample directory structure:

image-upload-app/
app.py
templates/
upload.html
static/
images/

Step 2: Creating an Upload Form

Create an HTML form for users to upload images. Here's a basic structure for your upload form template (upload.html):

<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
</head>
<body>
<header>
<h1>Image Upload</h1>
</header>
<section>
<h2>Upload an Image</h2>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*" required>
<button type="submit">Upload</button>
</form>
</section>
</body>
</html>

Step 3: Handling Image Uploads

Create a route to handle image uploads. Use Flask's `request` object to access the uploaded file. Here's an example of the route in your Flask app:

# app.py
from flask import Flask, render_template, request, redirect, url_for, flash
import os
app = Flask(__name)
app.secret_key = 'your_secret_key' # Replace with your secret key
app.config['UPLOAD_FOLDER'] = 'static/images'
@app.route('/')
def upload_form():
return render_template('upload.html')
@app.route('/upload', methods=['POST'])
def upload_image():
if 'image' not in request.files:
flash('No file part')
return redirect(request.url) file = request.files['image']
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file:
filename = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(filename)
flash('Image uploaded successfully')
return redirect(url_for('upload_form'))
if __name__ == '__main__':
app.run(debug=True)

Step 4: Displaying Uploaded Images

To display uploaded images, you can use an `` tag in your HTML templates. Here's an example of how you can display an uploaded image on a web page:

<!DOCTYPE html>
<html>
<head>
<title>Display Image</title>
</head>
<body>
<header>
<h1>Uploaded Image</h1>
</header>
<section>
<h2>Image Preview</h2>
<img src="{{ url_for('static', filename='images/your_uploaded_image.jpg') }}" alt="Uploaded Image">
</section>
</body>
</html>

Conclusion

Implementing image uploads in Flask is a valuable feature for web applications. By following the steps in this guide, you can set up an image upload form, handle image uploads, and display uploaded images on your web pages. Enhance your web application by allowing users to upload and view images.