Flask / Flask File Uploads and Media Handling

Managing File Paths and Storage

Get to grips with managing file paths and storage in Flask with this step-by-step tutorial.

Tutorial 4 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

Welcome to this tutorial on managing file paths and storage in Flask. Flask is a popular web framework for Python, renowned for its simplicity and flexibility. One important aspect of web development with Flask is managing file paths and storage, which is what this tutorial will cover.

By the end of this tutorial, you will understand:
- How to manage file paths within your Flask application
- How to handle file storage and retrieval

Prerequisites:
- Basic understanding of Python
- Familiarity with Flask is helpful, but not mandatory

2. Step-by-Step Guide

In Flask, you will typically manage file paths when serving static files (like CSS, JavaScript, and images) and when handling file uploads/downloads.

File Paths: Flask considers all paths from the root directory of your application. For instance, if you have a directory named static in your root directory, you can access a file inside it as static/filename.

File Storage: When you handle file uploads, you need to decide where to store them. A common approach is to save them in a subdirectory of your application, like uploads.

Best Practices:

  • Keep your static files in a separate directory named static.
  • Don't store uploaded files in your application directory. Use a separate storage service or a well-protected directory.

3. Code Examples

Here's an example of how to serve a static file and handle a file upload:

from flask import Flask, request, send_from_directory
import os

app = Flask(__name__)
UPLOAD_FOLDER = '/path/to/upload/folder'

# Serving a static file
@app.route('/static/<path:filename>')
def serve_static_file(filename):
    # Use send_from_directory to safely serve the file
    return send_from_directory('static', filename)

# Handling a file upload
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            return 'No file part'
        file = request.files['file']
        # if user does not select file, browser also submits an empty part without filename
        if file.filename == '':
            return 'No selected file'
        if file:
            file.save(os.path.join(UPLOAD_FOLDER, file.filename))
            return 'File uploaded successfully'

In the first route, we use send_from_directory to serve a file from the static directory.

In the second route, we handle a file upload. If the uploaded file exists, we save it in our UPLOAD_FOLDER.

4. Summary

In this tutorial, we learned how to manage file paths and storage in Flask. We've seen how to serve static files and handle file uploads.

Next, you could learn more about file handling, like how to validate uploaded files or how to handle large files.

5. Practice Exercises

  1. Create a Flask route that serves a file from a directory other than static.
  2. Modify the file upload example to only allow files with a .txt extension.

Here's a solution for the second exercise:

from werkzeug.utils import secure_filename

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            return 'No file part'
        file = request.files['file']
        if file.filename == '':
            return 'No selected file'
        if file and file.filename.endswith('.txt'):
            filename = secure_filename(file.filename)
            file.save(os.path.join(UPLOAD_FOLDER, filename))
            return 'Text file uploaded successfully'
        else:
            return 'Invalid file type. Only .txt files allowed.'

In this solution, we use secure_filename to make sure the filename is secure. We also check the file extension before saving the file.

Happy coding!

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

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Robots.txt Generator

Create robots.txt for better SEO management.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

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