Upload Files Using HTML Forms

In this exercise, you will add file uploads to the code in Exercise 4.1 (the user will be able to upload a picture with the form).

Add a Picture Upload

To add a picture upload, change the form as follows:

Before
After

The <input type=file> tag allows the user to upload a file, but the <form> will not submit properly without method="POST" and enctype="multipart/form-data" attributes.

The attribute accept=".png, .jpg, .jpeg, .gif" creates some front end validation of file types.

Take note that like all front-end validation, this file type validation can be disabled easily by the user. Test this by simply adding the novalidate attribute to the form using Developer Tools => Elements.

Receive File on Back End

Create a directory in your project folder to save uploaded files. The code below expects it to be called uploads/, but you can call it what you want so long as you make the code match. Add the following code below to app.py in the alert_post route after the lines getting the name, location, and need variables:

Add to app.py (alert_post route)

Make It More Secure

At this point, the user could upload any file with any name. So long as the user disables front end validation, they could upload a document with any name, any file extension, invalid filenames designed to probe weaknesses, etc. and this should probably concern you. It is usually considered good practice to deal with these concerns by validating file extensions on the back end (where the user can't disable it) and change file names in some way. Add code that does this.

The following code is sufficient for demo purposes. It sanitizes the filename using the secure_filename function (which removes invalid characters and characters often used in hacking). It creates an error message if the extension is wrong. Otherwise, it renames the uploaded file threat.png or threat.jpg or threat.[whatever extension is used] before saving it. The code below creates some functions for model.py (to keep with MVC design), then uses these functions in app.py to validate. Since this code dumbly overwrites the file every time a user uploads one, feel free to experiment with how the file is named.

Create model.py
Create model.py