Flask Programming

Hands On No. 10 : File Upload Demo

Resources

Source Code of hello.py
from flask import Flask
from flask import render_template
from flask import request
from werkzeug.utils import secure_filename
import os

app = Flask(__name__, template_folder='templates')

@app.route("/")
def index():
    return render_template('index.html')

@app.route('/savedata', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['the_file']
        temp = 'static/temp/' + str(secure_filename(f.filename))
        f.save(temp)
        return 'file uploaded successfully'

@app.route('/listfiles')
def listfiles():
    entries = os.listdir('static/temp/')
    return render_template('List-Files.html', entries=entries)

Source Code of index.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>

<div class="container">


<form action="/savedata" method="POST" enctype="multipart/form-data">
<div>
<label for="formFileLg" class="form-label">Upload File</label>
<input class="form-control form-control-lg" id="formFileLg" type="file" name="the_file">
</div>
<div>

<button type="submit" class="btn btn-primary">Upload</button>
</div>

</form>

</div>

</body>
</html>

Source Code of List-Files.html

<!DOCTYPE html>
<html>
<head>
<title>List Files</title>
</head>
<body>
<ul>
{% for item in entries %}
<li><a href='static/temp/{{ item }}'>{{ item }}</a> </li>
{% endfor %}
</ul>
</body>
</html>