To upload file in flask python is very important. Even if we are trying to upload the profile image with even very basic profile management task with flask. Or we are trying to create an e-commerce website with flask python and need to upload product images. We always need to implement file uploading method if we are building some web application with flask. Even for a simplest IoT web application with flask python require a file uploading method.

File uploading could be a csv file upload to flask python or image upload with flask python. One important thing to remember is that the file type submitted from the html form should be multipart/form-data. This will tell the backend server that we are trying to upload the file. In backend which in our case is the flask python backend, will automatically receive the file and with the simple os library we can save that file in upload folder.

Specify Upload folder in Flask

Here it comes next important point that we have to specify the upload folder in Python Flask application. Even if you are trying to make a very simple IoT application which need the file upload method. Or you are running the flask server in your local host computer you have to mention the upload folder. You can simply do this with the help of configuration settings available in flask framework. Here is the simplest example of specifying the upload directory in the flask python web application.

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
Code language: JavaScript (javascript)

Here you can clearly see, we mentioned the upload folder with the name uploads. Now you should make sure that the uploads directory is available. This should be at the root level. where you actual file is. If you are not familiar with basic flask application startup you may like to see the basic hello world application in flask python. This previous post about the basic startup of flask application will give you idea of how the basic flask application will looks like and how you can start your own flask python web application.

Create Upload.html file

Now you need to implement the frontend for uploading the file to the backend. To do this, we have to build a simple html form of type multipart/form-data in the upload.html file. We have to specify the input field as file type in that form. We also need one submit button to send that file to the backend. Here is how a form will look like with a file input upload the file to the backend.

    <form action="/upload" method="POST" enctype="multipart/form-data">
        <input type="file" name="image" accept="image/*" required>
        <button type="submit">Upload</button>
    </form>Code language: HTML, XML (xml)

Here you can see that we specify the enctype=”multipart/form-data”. This will tell that we are submitting data other than the usual text fields.

Receiving file on Flask Backend

Now we submitted the file through form. We are ready to receive this file in flask backend. We need to implement the upload route which will handle the post request. The multipart data in form of multipart will received in the backend. Here is the code for the upload route in flask python backend code.

def index():
    return render_template('upload.html')

@app.route('/upload', methods=['POST'])
def upload():
    if 'image' not in request.files:
        return "No file part"
    image = request.files['image']

    if image.filename == '':
        return "No selected file"
    # Ensure a secure filename (e.g., using UUID)
    filename = str(uuid.uuid4()) + os.path.splitext(image.filename)[1]
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)

    return f"Image uploaded successfully! Filepath: <a href='/uploads/{filename}'>{filepath}</a>"Code language: PHP (php)

To create a unique name to create with the uuid package here is the line.

    filename = str(uuid.uuid4()) + os.path.splitext(image.filename)[1]

This code will return that file name with <a> tag to let user know the file name to access.

Serve the Image from file

Once we saved the file into the uploads folder. We are ready to serve it whenever user request. The user have to remember the file name. Which is very difficult. The usual method for this is to save the filename in the database. We are not handling database in this post. We are simply creating another route which will handle the request to serve the file from directory. Here is the complete code for this image serving from file.

def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)Code language: JavaScript (javascript)

The above code is dynamic routing where we define a route with filename attribute. The filename could be anything and the route will work. We use the filename as an argument to the uploaded_file(filename): function which serve the file from directory. We are using the flask built in function to serve the file. Which means you have to import it from the flask like following.

from flask import Flask, render_template, request, redirect, url_for,send_from_directoryCode language: JavaScript (javascript)


Here are some useful links which will help you to further study this topic.

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.