0
0
FlaskDebug / FixBeginner · 4 min read

How to Handle File Upload in Flask: Fixes and Best Practices

To handle file upload in Flask, use request.files to get the uploaded file and save it securely with file.save(). Make sure your HTML form uses enctype="multipart/form-data" and the Flask route allows POST requests.
🔍

Why This Happens

Many beginners forget to set the form's encoding type or incorrectly access the uploaded file, causing errors or empty uploads.

Also, trying to access request.form instead of request.files for files leads to missing file data.

python
from flask import Flask, request

app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']  # Corrected: files are in request.files
    file.save('/path/to/save/' + file.filename)
    return 'File uploaded!'

if __name__ == '__main__':
    app.run(debug=True)
Output
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: KeyError: 'file'
🔧

The Fix

Change the form to use enctype="multipart/form-data" and access the file using request.files['file']. Then save the file securely.

python
from flask import Flask, request, render_template_string
import os

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

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    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:
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
            file.save(filepath)
            return f'File uploaded to {filepath}'
    return render_template_string('''
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="file">
            <input type="submit" value="Upload">
        </form>
    ''')

if __name__ == '__main__':
    os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
    app.run(debug=True)
Output
When accessed via browser, shows a file upload form; after upload, shows 'File uploaded to ./uploads/filename'
🛡️

Prevention

Always set your HTML form's enctype to multipart/form-data when uploading files.

Use request.files to access uploaded files, not request.form.

Validate the file presence and filename before saving to avoid errors.

Use secure filenames and configure an upload folder to keep files organized and safe.

⚠️

Related Errors

KeyError on file key: Happens if the form does not send the file or the key name is wrong.

Empty filename: Occurs if no file is selected before submitting.

Permission errors: When saving files to a folder without write permission.

Key Takeaways

Use enctype="multipart/form-data" in your HTML form for file uploads.
Access uploaded files with request.files['file'], not request.form.
Always check if the file exists and has a valid filename before saving.
Save files to a designated upload folder with proper permissions.
Validate and sanitize filenames to avoid security risks.