0
0
Flaskframework~5 mins

Serving uploaded files in Flask

Choose your learning style9 modes available
Introduction

Serving uploaded files lets users access files they have sent to your app. It makes the files available through a web link.

You want users to download images or documents they uploaded.
You need to show uploaded profile pictures on user pages.
You want to allow users to share files via URLs.
You want to serve files stored on your server safely.
You want to handle file downloads in your web app.
Syntax
Flask
from flask import send_from_directory

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory('uploads', filename)

send_from_directory safely sends files from a folder.

The folder name is relative to your app's root folder.

Examples
This example serves files from a folder named user_uploads. It supports subfolders because of path:filename.
Flask
from flask import send_from_directory

@app.route('/files/<path:filename>')
def serve_file(filename):
    return send_from_directory('user_uploads', filename)
This serves image files stored inside static/images folder.
Flask
from flask import send_from_directory

@app.route('/images/<filename>')
def serve_image(filename):
    return send_from_directory('static/images', filename)
Sample Program

This Flask app lets users upload a file via a form. After uploading, it saves the file in the uploads folder. Then it redirects the user to a URL where the uploaded file is served back using send_from_directory.

This way, users can upload and then view or download their files easily.

Flask
from flask import Flask, request, redirect, url_for, send_from_directory
import os

app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

os.makedirs(UPLOAD_FOLDER, exist_ok=True)

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files.get('file')
        if file:
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
            file.save(filepath)
            return redirect(url_for('uploaded_file', filename=file.filename))
    return '''
    <h1>Upload a file</h1>
    <form method="post" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="submit" value="Upload">
    </form>
    '''

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always validate and sanitize filenames to avoid security risks.

Use send_from_directory instead of send_file for safer file serving.

Make sure the upload folder exists and has correct permissions.

Summary

Use send_from_directory to serve uploaded files safely.

Set up a route that takes a filename and returns the file from your upload folder.

After uploading, redirect users to the file URL to access their files.