Creating an image gallery with the ability to upload and display images is a common feature in web applications. In this guide, we'll explore how to implement image uploading and create a gallery using Flask, a Python web framework. You'll learn how to set up image uploading, handle file storage, and display images in a gallery format. By following this guide, you'll have the knowledge and code to add image galleries to your web projects, such as a personal portfolio or a community photo-sharing platform.

Step 1: Setting Up Your Flask Application

Start by setting up your Flask application and creating a directory structure. Here's a sample structure:


Step 2: Creating the Image Gallery

Create a Flask application for the image gallery. Here's an example of the Python code:

from flask import Flask, render_template, request, redirect, url_for
from werkzeug.utils import secure_filename
import os
app = Flask(__name)
app.config['UPLOAD_FOLDER'] = 'static/uploads'
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
def gallery():
image_files = [f for f in os.listdir(app.config['UPLOAD_FOLDER']) if allowed_file(f)]
return render_template('gallery.html', image_files=image_files)
@app.route('/upload', methods=['POST'])
def upload_image():
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
if file.filename == '':
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)['UPLOAD_FOLDER'], filename))
return redirect(url_for('gallery'))
if __name__ == '__main__':

Step 3: Creating HTML Templates

Create an HTML template for the image gallery. Here's an example:

<!-- templates/gallery.html -->
<!DOCTYPE html>
<title>Image Gallery</title>
<h1>Image Gallery</h1>
<h2>Upload an Image</h2>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" accept=".jpg, .jpeg, .png, .gif">
<button type="submit">Upload</button>
<div class="image-gallery">
{% for image_file in image_files %}
<img src="{{ url_for('static', filename='uploads/' + image_file) }}" alt="Image">
{% endfor %}

Step 4: Running Your Image Gallery

Run your Flask image gallery using the following command:


Access your image gallery in a web browser, upload images, and view them in the gallery format.


Implementing image uploading and creating an image gallery with Flask is a valuable addition to web projects that involve images. By following the steps in this guide, you can set up image uploading, handle file storage, and display images in a gallery. This project can serve as a starting point for more advanced image management features, including user accounts, image tagging, and image metadata.