Flask

Flask and Image Uploading - Creating a Gallery


Introduction

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:

image-gallery/
    app.py
    static/
        uploads/
    templates/
        gallery.html
    

Step 2: Creating the Image Gallery

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

# app.py
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']
@app.route('/')
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)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return redirect(url_for('gallery'))
if __name__ == '__main__':
    app.run(debug=True)
        

Step 3: Creating HTML Templates

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

<!-- templates/gallery.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Image Gallery</title>
</head>
<body>
    <header>
        <h1>Image Gallery</h1>
    </header>
    <section>
        <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>
        </form>
    </section>
    <section>
        <h2>Images</h2>
        <div class=`image-gallery`>
            {% for image_file in image_files %}
                <img src=`{{ url_for('static', filename='uploads/' + image_file) }}` alt=`Image`>
            {% endfor %}
        </div>
    </section>
</body>
</html>
        

Step 4: Running Your Image Gallery

Run your Flask image gallery using the following command:

python app.py
        

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

Conclusion

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.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.