The tutorial, Python flask file upload example, will show you how to upload single or multiple files using Python 3 and Flask technologies.

Prerequisites

Have Python installed in Windows (or Unix)
Pyhton version and Packages
I am using Python 3.6.6 version

Please go through the following steps in order to implement Python flask file upload example.

Step 1. Create the below app.py script(py is the extension to indicate Python script) where we import the flask module. Notice how we create flask instance. Here we need to assign secret key otherwise flash will not work in Python.

In the below script we import the required module – Flask. If you do not have this module then install it.

Here we have also specified the file upload folder and maximum size of the file to be uploaded as 16MB.

from flask import Flask

UPLOAD_FOLDER = 'D:/uploads'

app = Flask(__name__)
app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

Step 2. Next we need main.py script. This script is the perfect instance of Python flask file upload example. It defines all required URIs for performing file upload operations.

We have used upload.html page for uploading file to the desired directory.

We show success message on successful file upload.

import os
from app import app
from flask import Flask, flash, request, redirect, render_template
from werkzeug.utils import secure_filename

ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

def allowed_file(filename):
	return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
	
@app.route('/')
def upload_form():
	return render_template('upload.html')

@app.route('/', methods=['POST'])
def upload_file():
	if request.method == 'POST':
        # check if the post request has the file part
		if 'file' not in request.files:
			flash('No file part')
			return redirect(request.url)
		file = request.files['file']
		if file.filename == '':
			flash('No file selected for uploading')
			return redirect(request.url)
		if file and allowed_file(file.filename):
			filename = secure_filename(file.filename)
			file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
			flash('File(s) successfully uploaded')
			return redirect('/')

if __name__ == "__main__":
    app.run()

Step 3. Now we need template page for uploading file. This is upload.html page kept under subdirectory – templates. You can use this page for uploading single or multiple files. If you want to upload multiple files then you need to hold CTRL key and select files.

<doctype html>
<title>Python Flask File Upload Example</title>
<h2>Select file(s) to upload</h2>
<p>
	{% with messages = get_flashed_messages() %}
	  {% if messages %}
		<ul class=flashes>
		{% for message in messages %}
		  <li>{{ message }}</li>
		{% endfor %}
		</ul>
	  {% endif %}
	{% endwith %}
</p>
<form method="post" action="/" enctype="multipart/form-data">
    <dl>
		<p>
			<input type="file" name="file" multiple="true" autocomplete="off" required>
		</p>
    </dl>
    <p>
		<input type="submit" value="Submit">
	</p>
</form>

Testing of the application

When you open the default URL http://localhost:5000 then you will see below page:

python flask file upload

When you select a file for upload: you can select only the specified types of files as in the main.py script.

python flask file upload

When you click on Submit button after selecting a file or files:

python flask file upload

Now you check the uploaded file in the destination:

python flask file upload

That’s all. Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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