flask
  1. flask-file-uploading

File Uploading in Flask

Files uploading is an essential part of web development. Flask provides a simple way to upload files on the server and process them as per the requirement.

Syntax

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':
        f = request.files['file']
        filename = secure_filename(f.filename)
        f.save(filename)
        return 'file uploaded successfully'
        
    else:
        return render_template('upload.html')

Example

Here's an example to upload a file using Flask.

from flask import Flask, request, render_template
from werkzeug.utils import secure_filename

app = Flask(__name__)

# HTML template to allow users to upload files
@app.route('/')
def upload_form():
    return render_template('upload.html')

# route to handle the uploaded file
@app.route('/', methods=['POST'])
def upload_file():
    file = request.files['inputFile']
    filename = secure_filename(file.filename)
    file.save(filename)
    return 'File saved successfully'

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

Output

The code will save the uploaded file to the server.

Explanation

In the upload_file function, we first check if the request method is POST or not. If it is then get the uploaded file using the request module then get the filename using secure_filename function from the werkzeug.utils module. After getting the filename, save the file using the save method.

Use

File uploading can be used for various purposes like uploading images in a social media platform, uploading user-generated content in a blogging platform, or simply letting the users upload any file that the website requires.

Important Points

  1. Flask provides a simple way to upload files on the server.
  2. Always validate and sanitize user input for security reasons before processing a file upload.
  3. Always use the secure_filename method to avoid issues in special characters in the filenames.

Summary

This tutorial covers how to handle file uploads in Flask using the request module. Users can successfully upload files on the server and can be processed as per the requirements.

Published on: