Upload a File with Python Flask with Examples

File uploads are a common feature in web applications, allowing users to send files to the server for processing or storage. Python's Flask framework makes handling file uploads straightforward and efficient. In this blog post, we will explore how to create a simple file upload functionality using Flask, complete with code examples.

 

Upload a File with Python Flask with Examples

 

 

Setting Up Your Flask Environment


Before diving into the code, ensure you have Flask installed.  


 


pip install flask


Create a new directory for your project and set up a basic Flask application: 

 



from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'  # Directory where uploaded files will be stored
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # Maximum file size limit (16 MB)

# Make sure the upload folder exists
import os
if not os.path.exists(app.config['UPLOAD_FOLDER']):
    os.makedirs(app.config['UPLOAD_FOLDER'])

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

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


This basic setup includes configuration for the upload folder and a maximum file size limit. The `UPLOAD_FOLDER` is where the uploaded files will be saved, and the `MAX_CONTENT_LENGTH` is set to 16 MB to prevent users from uploading excessively large files.
 
 

Creating the HTML Form


Next, create a simple HTML form for file uploads. Save this as `templates/index.html`:
 
 

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


This form uses the `POST` method and the `multipart/form-data` encoding type, which is necessary for file uploads.
 

Handling File Uploads in Flask


Now, let's add the route to handle the file upload:
 
 

from werkzeug.utils import secure_filename

# Allowed file extensions
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'txt'}

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:
        return "No file part"
    
    file = request.files['file']
    if file.filename == '':
        return "No selected file"
    
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return redirect(url_for('uploaded_file', filename=filename))
    
    return "File type not allowed"

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return f"File {filename} uploaded successfully"

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


In this code:


1. We define a helper function `allowed_file` to check if the uploaded file has an allowed extension.
2. The `/upload` route processes the uploaded file. It first checks if a file is part of the request, then ensures the file has a valid name and extension.
3. If the file passes all checks, it is saved to the `UPLOAD_FOLDER` directory.
4. After saving the file, the user is redirected to a new route (`/uploads/<filename>`) that confirms the successful upload.
 

Running the Application


To run your application, execute the Python script:
 
 

python app.py


Navigate to `http://127.0.0.1:5000/` in your web browser. You should see the file upload form. Select a file and click "Upload". If everything is set up correctly, you will be redirected to a confirmation page indicating the file was uploaded successfully.
 

Full summary code:

 

index.html




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


app.py




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

app = Flask(__name__)

# Configuration
app.config['UPLOAD_FOLDER'] = 'uploads/'  # Directory where uploaded files will be stored
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # Maximum file size limit (16 MB)

# Ensure the upload folder exists
if not os.path.exists(app.config['UPLOAD_FOLDER']):
    os.makedirs(app.config['UPLOAD_FOLDER'])

# Allowed file extensions
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'txt'}


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


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


@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return "No file part"

    file = request.files['file']
    if file.filename == '':
        return "No selected file"

    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return redirect(url_for('uploaded_file', filename=filename))

    return "File type not allowed"


@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return f"File {filename} uploaded successfully"


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



 

Conclusion


Uploading files with Flask is a straightforward process. By following the steps outlined in this guide, you can implement a robust file upload feature in your Flask application. Remember to validate file types and sizes to ensure your application remains secure and performs efficiently.

Feel free to extend this example by adding more sophisticated error handling, integrating with a database, or processing uploaded files based on your application's requirements.


Previous Post Next Post