File Uploads
create a new folder in your webroot called files, make sure it has correct permissions set for write access
template.html:<!doctype html> <title>file uploader</title> <form action="/upload" method="post" enctype="multipart/form-data"> Select file to upload:<br> <input type="file" name="fileToUpload" id="fileToUpload"> <br> <input type="submit" value="upload file" name="submit"> </form>site.py:
from flask import Flask from flask import render_template from flask import request import os app = Flask(__name__) app.config["uploadFolder"] = "/inetpub/wwwroot/files/" @app.route("/upload", methods=["POST"]) def upload(): file = request.files["fileToUpload"] file.save(os.path.join( app.config["uploadFolder"], file.filename)) return render_template("template.html") @app.route("/") def start(): return render_template("template.html") app.run(host="0.0.0.0", port=5000, debug=True)
Challenges
- develop your own simple photo repository, where users can upload photos and browse exisiting image files
help
if you have followed the uploader example above, move your uploaded files into a new static\ folder in your webroot
template.html:
site.py:<!doctype html> <title>file uploader</title> <form action="/upload" method="post" enctype="multipart/form-data"> Select file to upload:<br> <input type="file" name="fileToUpload" id="fileToUpload"> <br> <input type="submit" value="upload file" name="submit"> </form> {% for eachFile in fileList %} <img src="{{ url_for('static',filename='uploads/'+eachFile) }}"> {% endfor %}
from flask import Flask from flask import render_template from flask import request import os app = Flask(__name__) app.config["uploadFolder"] = "/inetpub/wwwroot/static/uploads" @app.route("/upload", methods=["POST"]) def upload(): file = request.files["fileToUpload"] file.save(os.path.join( app.config["uploadFolder"], file.filename)) return render_template("template.html", fileList=getFileList()) @app.route("/") def start(): return render_template("template.html", fileList=getFileList()) def getFileList(): dirListing = os.listdir(app.config["uploadFolder"]) fileList = [] for file in dirListing: fileList.append(file) return fileList app.run(host="0.0.0.0", port=5000, debug=True)
- use session variables to secure the photo gallery resource to logged in patrons only
- implement search by filename functionality into your photo gallery app