Introduction
The tutorial, Python flask file upload example, will show you how to upload single file using Python 3 and Flask web framework. You may also find useful example on file upload on different technologies.
In this file upload example I am going to show you how to select single file and upload in the server.
Related Posts:
- Python Flask REST API File Upload Example
- Python Flask Multiple Files Upload Example
- Python Flask REST API Multiple Files Upload
Prerequisites
Python 3.6.6 – 3.9.1, Flask 1.1.1 – 1.1.2 (pip install flask
)
Project Directory
Create a project root directory called python-flask-file-upload as per your chosen location.
I may not mention the project’s root directory name in the subsequent sections but I will assume that I am creating files with respect to the project’s root directory.
App Configuration
Create the below app.py script(py is the extension to indicate Python script) where I need to import the flask module. Notice how I create flask instance. Here I need to assign a secret key otherwise flash will not work in Python.
In the below script I import the required module – Flask. If you do not have this module then install it using the command pip install flask
.
Here I 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
File Upload
Next I create 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.
I have used upload.html page for uploading file to the desired directory. In the next section I will talk about this template file – upload.html.
I show success message on successful file upload.
import os
#import magic
import urllib.request
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 successfully uploaded')
return redirect('/')
else:
flash('Allowed file types are txt, pdf, png, jpg, jpeg, gif')
return redirect(request.url)
if __name__ == "__main__":
app.run()
Template File – UI
Now I need a template page for uploading file. This is upload.html page kept under subdirectory – templates. This templates directory is the standard folder in the flask based web application. You can use this page for uploading single file.
<!doctype html>
<title>Python Flask File Upload Example</title>
<h2>Select a file 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" autocomplete="off" required>
</p>
</dl>
<p>
<input type="submit" value="Submit">
</p>
</form>
Deploying the Application
Now navigate to the project’s root directory using command line tool and execute the command python main.py
or simple main.py
, your server will be started on default port 5000.
If you want to change the port then you can change the line app.run()
to app.run(port=5001)
, where 5001 is the new port.
Testing the Application
When you open the default URL http://localhost:5000 then you will see below page:
When you select a file for upload: you can select only the specified types of files as in the main.py script.
When you click on Submit button after selecting a file or files:
Now you check the uploaded file in the destination:

That’s all about file upload example using Python and Flask.
Hi Roy,
Thanks fo sharing the article.
I am facing an error which says ModuleNotFoundError: No module named ‘app’.
I have saved the app.py file under the uploads folder. Your article says save it under Flask, but where do I find that?
Hi Akshay, please browse the github link. The same structure you have to follow.
Como eu consigo verificar o tamanho do arquivo e a extensão?
How did you start the local server?
Executing main.py file will start the local server
Artigo muito bom, obrigado de certo!
Amazing guide! Is there a way to display the image uploaded on to the page?
Yes it is possible but I don’t have a guide right now
Awesome guide. Helped me a lot
Appreciate your tutorial – sign up for bat so I can support
Thanks, this article was really useful and straight to the point!
I am facing a 404 issue when the run the code.
This only works with a HTML form – how can you correct this so you can call it from any external client, ex postman ? if you try from postman request.files always will be 0 len.
You need to build REST API to upload from external clients.
After I uploaded the video, How can I redirect to video url?
Replace
return redirect('/')
byreturn redirect('your video url')
Hi,
Thanks for posting this solution. I am trying to create a python web app in VS2019 using this code. I have installed flask and werkzeug but I am getting an error on the import urllib.request (unresolved import ‘urllib.request’) . Do you have any advice on how to resolve this please? Many thanks!
This https://stackoverflow.com/questions/36965864/opening-a-url-with-urllib-in-python-3 may help you.
Thanks a lot for the detailed instructions. I am getting a 405 error though when submitting the request. Any idea how to resolve this?
405 means method not allowed. Please check your are posting request through correct http method that is defined on your server side.
when i select a pdf file and submit it throws me Internal server error
check what error you get in the browser log
this program can be used to upload only single file, how can i upload multiple files.
the html page provided here, is selecting multiple files but uploading only one.
help!!!!!!
Thanks for pointing out. Yes this is for uploading single file. I will post soon on how to upload multiple files.
Just wanted to thank you for how bare-bones this tutorial is. Got me exactly what I needed, when I needed it