0
0
Flaskframework~5 mins

File upload forms in Flask

Choose your learning style9 modes available
Introduction

File upload forms let users send files like images or documents to your website. This helps you collect data or let users share content easily.

When users need to upload profile pictures on a social site.
When collecting documents like resumes or reports from users.
When allowing users to share images or videos in a chat app.
When building an admin panel to upload files to the server.
When creating a form to submit attachments with feedback or support requests.
Syntax
Flask
from flask import Flask, request, render_template
from werkzeug.utils import secure_filename

app = Flask(__name__)

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files.get('file')
        if file and file.filename != '':
            filename = secure_filename(file.filename)
            file.save(f"uploads/{filename}")
            return 'File uploaded successfully'
    return render_template('upload.html')

Use request.files['file'] to get the uploaded file from the form.

The form must have enctype="multipart/form-data" to send files properly.

Examples
Basic HTML form to select and upload a file.
Flask
<form method="POST" enctype="multipart/form-data">
  <input type="file" name="file">
  <button type="submit">Upload</button>
</form>
Check if a file was uploaded and save it to the 'uploads' folder.
Flask
file = request.files.get('file')
if file and file.filename != '':
    file.save(f"uploads/{file.filename}")
Use secure_filename to avoid unsafe file names.
Flask
@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    if file:
        filename = secure_filename(file.filename)
        file.save(f"uploads/{filename}")
        return 'Upload done!'
    return 'No file selected'
Sample Program

This Flask app shows a simple file upload form. When a user picks a file and submits, the file is saved safely in the 'uploads' folder. It uses secure_filename to keep file names safe and includes accessibility with an aria-label.

Flask
from flask import Flask, request, render_template_string
from werkzeug.utils import secure_filename
import os

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

if not os.path.exists(app.config['UPLOAD_FOLDER']):
    os.makedirs(app.config['UPLOAD_FOLDER'])

UPLOAD_FORM = '''
<!doctype html>
<title>Upload File</title>
<h1>Upload a file</h1>
<form method="POST" enctype="multipart/form-data">
  <input type="file" name="file" aria-label="File upload">
  <button type="submit">Upload</button>
</form>
'''

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        file = request.files.get('file')
        if file and file.filename != '':
            filename = secure_filename(file.filename)
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(filepath)
            return f'File "{filename}" uploaded successfully.'
        return 'No file selected.'
    return render_template_string(UPLOAD_FORM)

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

Always check if a file was actually selected before saving.

Use secure_filename from werkzeug.utils to avoid security risks with file names.

Make sure the upload folder exists and your app has permission to write there.

Summary

File upload forms let users send files to your Flask app.

Use request.files and set form enctype to multipart/form-data.

Always save files safely using secure_filename and check for empty uploads.