Uploading and Downloading Files in Flask
×


Uploading and Downloading Files in Flask

1222

Uploading and Downloading Files in Flask

Introduction

Building a Flask web app often involves letting users upload files—like images, documents, or datasets—and later downloading processed content or originals. In this article, you'll learn how to manage file uploads and downloads securely and efficiently using Flask.

Project Setup

Create the following structure at the root of your project:

  • app.py – your Flask application
  • templates/ – for HTML files
  • uploads/ – where uploaded files are stored

Handling File Uploads

Enable file uploads by configuring your Flask app and creating a file upload form:

from flask import Flask, request, render_template, redirect, url_for
from werkzeug.utils import secure_filename
import os

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16 MB limit

ALLOWED_EXTENSIONS = {'png', 'jpg', 'txt', 'pdf'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

Upload Route and Form

Create a route to render the upload form and handle file submissions:

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files.get('file')
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(filepath)
            return redirect(url_for('download_file', filename=filename))
    return render_template('upload.html')

Upload Form Template

<!-- templates/upload.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload File</title>
</head>
<body>
    <h1>Upload your file</h1>
    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="file">
        <button type="submit">Upload</button>
    </form>
</body>
</html>

Serving File Downloads

After a file is uploaded, enable a download route:

from flask import send_from_directory

@app.route('/download/<filename>')
def download_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)

Sample Download Page

<!-- templates/download.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Download File</title>
</head>
<body>
    <h1>Your file is ready</h1>
    <a href="{{ url_for('download_file', filename=filename) }}">
        Download {{ filename }}
    </a>
</body>
</html>

Security Considerations

  • Always use secure_filename to sanitize filenames.
  • Restrict uploads by MIME type or extensions.
  • Limit file size to prevent denial-of-service via large uploads.
  • Store file paths securely, avoiding directory traversal risks.

Run and Test Your App

Launch your app locally:

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

Visit http://127.0.0.1:5000/, upload a permitted file, then click the provided download link to retrieve it.

Conclusion

“Uploading and Downloading Files in Flask” equips you to process file uploads, store them safely, and send files back to users. With proper validation, secure naming, and size restrictions, this flow is robust and ready for real-world applications.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat