0
0
Flaskframework~5 mins

File uploads handling in Flask

Choose your learning style9 modes available
Introduction

File uploads let users send files to your web app. Handling them correctly helps you save and use these files safely.

When users need to upload profile pictures.
When allowing users to submit documents or reports.
When building a form that accepts images or PDFs.
When you want to save user files on the server.
When processing files for further actions like analysis or display.
Syntax
Flask
from flask import Flask, request

app = Flask(__name__)

@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:
        file.save('/path/to/save/' + file.filename)
        return 'File uploaded successfully'

Use request.files to get uploaded files.

Always check if the file exists and has a filename before saving.

Examples
Saves the uploaded file to the '/uploads/' folder with its original name.
Flask
file = request.files['file']
file.save('/uploads/' + file.filename)
Checks if the file was sent in the request.
Flask
if 'file' not in request.files:
    return 'No file part'
Ensures the user selected a file before saving.
Flask
if file.filename == '':
    return 'No selected file'
Sample Program

This Flask app shows a simple page with a file upload form. When a user picks a file and submits, the file is saved to the 'uploads' folder on the server. It checks if a file was sent and if it has a name before saving.

Flask
from flask import Flask, request, render_template_string
import os

app = Flask(__name__)

UPLOAD_FOLDER = 'uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

@app.route('/')
def index():
    return render_template_string('''
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Upload File</title>
    </head>
    <body>
      <h1>Upload a File</h1>
      <form method="POST" action="/upload" enctype="multipart/form-data">
        <input type="file" name="file" aria-label="Choose file to upload" required>
        <button type="submit">Upload</button>
      </form>
    </body>
    </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'
    filepath = os.path.join(UPLOAD_FOLDER, file.filename)
    file.save(filepath)
    return f'File "{file.filename}" uploaded successfully to "{filepath}"'

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

Always use enctype="multipart/form-data" in your HTML form for file uploads.

Check file extensions and size to improve security before saving files.

Create the upload folder beforehand or use os.makedirs with exist_ok=True.

Summary

Use request.files to get uploaded files in Flask.

Always check if the file exists and has a filename before saving.

Save files to a safe folder and use proper HTML form encoding.