📖 Scenario: You are building a simple web app where users can upload a profile picture. The app needs a form to select a file and a way to handle the uploaded file on the server.
🎯 Goal: Create a Flask app with a file upload form. The form should let users pick a file. The server should accept the file and save it to a folder called uploads.
📋 What You'll Learn
Create a Flask app with a route for the upload form
Add an HTML form with enctype='multipart/form-data' and a file input named file
Configure a folder path variable called UPLOAD_FOLDER to save uploaded files
Write a route to handle POST requests, save the uploaded file to UPLOAD_FOLDER
💡 Why This Matters
🌍 Real World
File upload forms are common in web apps for profile pictures, documents, or media uploads.
💼 Career
Understanding file uploads is essential for backend web developers working with user-generated content.
Progress0 / 4 steps
1
Set up Flask app and upload folder
Create a Flask app by importing Flask and instantiating app = Flask(__name__). Then create a variable called UPLOAD_FOLDER and set it to the string 'uploads/'.
Flask
Hint
Remember to import Flask and create the app instance. The upload folder is just a string variable.
2
Create the HTML upload form route
Add a route @app.route('/') with a function called upload_form that returns a string with an HTML form. The form must have method='POST', enctype='multipart/form-data', and a file input with name='file'. Also include a submit button.
Flask
Hint
The form must use POST and multipart encoding to send files. The input's name must be exactly 'file'.
3
Add POST route to handle file upload
Modify the @app.route('/') decorator to accept both GET and POST methods. Inside upload_form, check if the request method is POST. If yes, get the uploaded file from request.files['file']. Then save the file to UPLOAD_FOLDER using file.save(). Import request from flask.
Flask
Hint
Use methods=['GET', 'POST'] in the route decorator. Use request.files['file'] to get the uploaded file.
4
Add app run command
Add the standard Flask app run block at the end: if __name__ == '__main__': and inside it call app.run(debug=True).
Flask
Hint
This block runs the Flask app when you start the script. Use debug=True for easier testing.
Practice
(1/5)
1. What must you set in the HTML form tag to allow file uploads in a Flask app?
easy
A. method="get"
B. enctype="multipart/form-data"
C. action="upload"
D. type="file"
Solution
Step 1: Understand form encoding for file uploads
File uploads require the form to send data in a special format that supports files, which is "multipart/form-data".
Step 2: Identify the correct form attribute
The form tag must have the attribute enctype="multipart/form-data" to handle file uploads correctly.
Final Answer:
enctype="multipart/form-data" -> Option B
Quick Check:
Form enctype = multipart/form-data [OK]
Hint: File uploads always need enctype multipart/form-data [OK]
Common Mistakes:
Using method="get" instead of post
Forgetting enctype attribute
Setting type="file" on form tag instead of input
Confusing action URL with encoding
2. Which Flask code correctly accesses an uploaded file named 'photo' from a form?
easy
A. file = request.form['photo']
B. file = request.args['photo']
C. file = request.data['photo']
D. file = request.files['photo']
Solution
Step 1: Identify where uploaded files are stored in Flask
Uploaded files are stored in request.files, not in request.form or request.args.
Step 2: Access the file by its form field name
Use request.files['photo'] to get the uploaded file object named 'photo'.
Final Answer:
file = request.files['photo'] -> Option D
Quick Check:
Uploaded files = request.files [OK]
Hint: Use request.files to get uploaded files, not request.form [OK]
Common Mistakes:
Using request.form to get files
Using request.args which is for URL params
Trying to access request.data as a dict
Misspelling 'files' or field name
3. What will the following Flask code print if no file is uploaded?
file = request.files.get('document')
if file and file.filename != '':
print('File received')
else:
print('No file uploaded')
medium
A. File received
B. KeyError exception
C. No file uploaded
D. Empty string printed
Solution
Step 1: Understand request.files.get behavior when no file sent
request.files.get('document') returns None if no file was uploaded with that name.
Step 2: Evaluate the if condition
Since file is None, the condition 'file and file.filename != ""' is False, so the else block runs.
Final Answer:
No file uploaded -> Option C
Quick Check:
No file means else prints [OK]
Hint: Check file is not None and filename not empty to confirm upload [OK]
Common Mistakes:
Assuming request.files['document'] raises error if missing
Not checking filename for empty string
Expecting 'File received' even if no file sent
Confusing request.files.get with request.files[]
4. Identify the error in this Flask file upload snippet:
A. secure_filename should be called on file.filename, not file
B. file.save() requires a file object, not a path
C. os.path.join cannot join strings
D. request.files['file'] returns a string, not a file object
Solution
Step 1: Check usage of secure_filename
secure_filename expects a string filename, but file is a file object, so file.filename should be passed.
Step 2: Confirm correct file saving steps
After getting a safe filename, join path and call file.save(path) correctly.
Final Answer:
secure_filename should be called on file.filename, not file -> Option A
Quick Check:
Pass filename string to secure_filename [OK]
Hint: Use secure_filename(file.filename), not file itself [OK]
Common Mistakes:
Passing file object to secure_filename
Confusing file.save argument type
Misusing os.path.join with non-string
Assuming request.files returns string
5. You want to allow users to upload multiple images at once and save only PNG files securely. What issue does this Flask code snippet have?
files = request.files.getlist('images')
for file in files:
if file and file.filename.endswith('.png'):
filename = secure_filename(file.filename)
file.save(os.path.join('uploads', filename))
hard
A. file.filename.endswith('.png') is case-sensitive and may miss '.PNG'
B. getlist() returns a single file, so loop will fail
C. secure_filename should be called after saving the file
D. This code correctly filters PNG files and saves them securely
Solution
Step 1: Understand getlist() usage
request.files.getlist('images') correctly returns a list of uploaded files for the field 'images'.
Step 2: Check file extension filtering
Using file.filename.endswith('.png') is case-sensitive and will miss files with uppercase extensions like '.PNG'.
Step 3: Confirm secure_filename usage
secure_filename is correctly called before saving the file.
Final Answer:
file.filename.endswith('.png') is case-sensitive and may miss '.PNG' -> Option A
Quick Check:
Check file extension case-insensitively [OK]
Hint: Check file extensions case-insensitively for uploads [OK]
Common Mistakes:
Assuming getlist returns one file
Calling secure_filename after saving
Ignoring uppercase file extensions
Not checking if file is None before saving
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.