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.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Explains 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

  1. Modify the Flask application to accept and display uploaded images.
  2. Add validation to only accept files of a certain type (e.g., .jpg and .png files).
  3. 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.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help