Camkode
Camkode

Mastering File Uploads in Flask: A Step-by-Step Guide

Posted by Kosal

Mastering File Uploads in Flask: A Step-by-Step Guide

File uploads are a common feature in web applications, allowing users to share images, documents, or other types of files. Flask, a lightweight and flexible web framework for Python, provides easy-to-use tools for handling file uploads securely. In this article, we'll walk through the process of implementing file uploads in a Flask application, covering everything from setting up the application to handling file uploads and ensuring security.

Setting up the Flask Application

To get started, make sure you have Flask installed. If not, you can install it via pip:

pip install Flask

Next, create a basic Flask application with a route to render an HTML form for file uploads.

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

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

Creating the HTML Form

In your HTML template (templates/index.html), create a form to allow users to upload files:

<!DOCTYPE html>
<html>
<head>
    <title>File Upload</title>
</head>
<body>
    <h2>Upload File</h2>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="Upload">
    </form>
</body>
</html>

Handling File Uploads in Flask

Add a route in your Flask application to handle file uploads and save the uploaded file securely:

import os
from flask import flash, redirect
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

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

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        flash('No selected file')
        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 'File uploaded successfully'
    else:
        return 'Invalid file format'

Ensuring Security

Ensure that you handle uploaded files securely by validating file extensions, renaming files, and storing them in a secure location. Use the secure_filename() function from the Werkzeug utility library to secure filenames.

Conclusion

With Flask, implementing file uploads in your web application is straightforward and secure. By following the steps outlined in this guide, you can enable users to upload files easily while ensuring that your application remains robust and protected against potential security threats. Whether you're building a photo-sharing platform, a document management system, or any other web application that requires file uploads, Flask provides the tools you need to get the job done efficiently and securely.