0
0
Flaskframework~5 mins

Saving uploaded files in Flask

Choose your learning style9 modes available
Introduction

Saving uploaded files lets your web app keep files users send, like photos or documents. This helps you use or share those files later.

When users upload profile pictures to your website.
When a form lets users submit documents or reports.
When you want to store images users add to a blog post.
When users upload files to share with others on your app.
Syntax
Flask
from flask import request

file = request.files['file']
file.save('/path/to/save/filename')
Use request.files to get the uploaded file from the form.
Call save() on the file object with the path where you want to store it.
Examples
Saves the uploaded file from the form field named 'photo' into the 'uploads' folder with the name 'profile.jpg'.
Flask
file = request.files['photo']
file.save('uploads/profile.jpg')
Checks if a file was uploaded under 'document' and saves it using its original filename inside 'uploads' folder.
Flask
uploaded_file = request.files.get('document')
if uploaded_file:
    uploaded_file.save(f"uploads/{uploaded_file.filename}")
Sample Program

This Flask app shows a simple form to upload a file. When a file is sent, it saves it in the 'uploads' folder and confirms the filename saved.

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('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files.get('file')
        if file:
            save_path = os.path.join(UPLOAD_FOLDER, file.filename)
            file.save(save_path)
            return f'File saved as {file.filename}'
        return 'No file uploaded'
    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__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always check if the file exists before saving to avoid errors.

Use secure filenames to avoid security risks (Flask has werkzeug.utils.secure_filename for this).

Make sure the folder where you save files exists and your app has permission to write there.

Summary

Use request.files to get uploaded files in Flask.

Call save() on the file object with a path to store it.

Check for file presence and use safe filenames to keep your app secure.