Upload and Play Video using Flask

In this example I am going to show you how to upload and play video using flask framework. Flask is a light weight web framework used to rapidly develop web applications in Python programming language. I am not validating the file type here but it is always good idea to validate the file type before user can upload the file to the server to avoid any kind of issues.

The uploaded video may or may not be played automatically but the uploaded video will have controls, such as, paly, pause, full screen, mute, unmute, download, etc.

Related Posts:

An upload form is displayed to the end user for browsing and selecting a video file that will be uploaded and displayed on the browser. I am using HTML5 tag to play the video. Make sure your browser supports HTML5 tag for playing video.

Prerequisites

Python 3.9.5, Flask 1.1.2

Project Directory

Create a project root directory called python-flask-upload-play-video 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.

upload and play video

Configure Flask Application

I will configure application through flask framework. I will also define the file upload location and maximum size of the file a user can upload.

You should not allow user to upload unlimited size of file due to security reasons or to avoid exhausting server space.

The standard directory for storing static resources such as images, css, javascript files into Flask application is to put under static directory. Here I am putting the uploaded file under static/uploads directory from where finally you will display the video on the web page.

Create a file called app.py with the below code.

from flask import Flask

UPLOAD_FOLDER = 'static/uploads/'

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

Configure Endpoint

Next I will create main.py script to configure the endpoint for uploading video file. It defines the required URIs for performing file upload operations.

I am using http method POST to upload the video file. After uploading and saving the video to disk I am returning the filename to the jinja2 flask template.

I have another function display_video() that is used on the flask template to display the actual video from the static/uploads folder.

This below line is required when you want to serve the video file from static folder only.

return redirect(url_for('static', filename='uploads/' + filename), code=301)

The whole code for the main.py file is given below:

import os
from app import app
import urllib.request
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
	
@app.route('/')
def upload_form():
	return render_template('upload.html')

@app.route('/', methods=['POST'])
def upload_video():
	if 'file' not in request.files:
		flash('No file part')
		return redirect(request.url)
	file = request.files['file']
	if file.filename == '':
		flash('No image selected for uploading')
		return redirect(request.url)
	else:
		filename = secure_filename(file.filename)
		file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
		#print('upload_video filename: ' + filename)
		flash('Video successfully uploaded and displayed below')
		return render_template('upload.html', filename=filename)

@app.route('/display/<filename>')
def display_video(filename):
	#print('display_video filename: ' + filename)
	return redirect(url_for('static', filename='uploads/' + filename), code=301)

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

View or Template File

Now you need a template page for uploading file as well as it will also display/play the uploaded video. This is upload.html page kept under directory – templates, which is the standard directory for storing template or view file in flask application.

<!doctype html>
<title>Python Flask - Video Upload and Play Example</title>
<h2>Select a video to upload and play</h2>
<p>
	{% with messages = get_flashed_messages() %}
	  {% if messages %}
		<ul>
		{% for message in messages %}
		  <li>{{ message }}</li>
		{% endfor %}
		</ul>
	  {% endif %}
	{% endwith %}
</p>
{% if filename %}
	<div style="margin: 10px auto;">
		<video autoplay="autoplay" controls="controls" preload="preload">
			<source src="{{ url_for('display_video', filename=filename) }}" type="video/mp4"></source>
		</video>
	</div>
{% endif %}
<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="Upload">
	</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 if your Python is on the classpath then just execute 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 hit the URL http://localhost:5000 in the browser to get the below page to upload the video.

upload and play video using flask

Once you select a video and upload then you will see the following screen:

upload and play video using flask

Hope you got an idea how to upload and play video using Python based web framework Flask.

Source Code

Download

Leave a Reply

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