📖 Scenario: You are building a simple web app where users can upload a text file. The app will read the file and display its content on the page.
🎯 Goal: Create a Flask app that accepts a file upload from a form, reads the file content, and shows it on the webpage.
📋 What You'll Learn
Create a Flask app with a route to show an upload form
Add a configuration variable to limit the maximum file size
Write code to handle the uploaded file and read its content
Display the uploaded file content on the webpage
💡 Why This Matters
🌍 Real World
File upload is common in web apps for user profile pictures, documents, or data import.
💼 Career
Understanding file upload handling is essential for backend web developers working with user input and file storage.
Progress0 / 4 steps
1
Create the Flask app and upload form
Write code to create a Flask app called app and add a route '/' that returns an HTML form with method='POST' and enctype='multipart/form-data'. The form should have a file input named file and a submit button.
Flask
Hint
Use Flask(__name__) to create the app. Use @app.route('/', methods=['GET', 'POST']) to define the route. Return a string with the HTML form including method='POST' and enctype='multipart/form-data'.
2
Add max file size configuration
Add a configuration variable MAX_CONTENT_LENGTH to the app.config and set it to 1 * 1024 * 1024 (1 megabyte).
Flask
Hint
Set app.config['MAX_CONTENT_LENGTH'] to 1 * 1024 * 1024 to limit uploads to 1MB.
3
Handle file upload and read content
Inside the upload function, check if the request method is 'POST'. Then get the uploaded file from request.files['file']. Read the file content as a string using file.read().decode('utf-8') and store it in a variable called content.
Flask
Hint
Use request.method == 'POST' to check the form submission. Access the file with request.files['file']. Read and decode the file content with file.read().decode('utf-8').
4
Display uploaded file content on the page
Modify the upload function to return an HTML page that shows the uploaded file content inside a <pre> tag for preserving formatting. Use render_template_string to return the HTML with the variable content safely embedded.
Flask
Hint
Use render_template_string with a template string that includes <pre>{{ content }}</pre> to show the file content safely.
Practice
(1/5)
1. What does request.files in Flask represent when handling file uploads?
easy
A. A dictionary-like object containing uploaded files
B. A list of all form fields submitted
C. A string with the file path on the server
D. A function to save files automatically
Solution
Step 1: Understand request.files role
It holds files sent by the client in a dictionary-like object where keys are input names.
Step 2: Differentiate from other request parts
Unlike form fields in request.form, request.files specifically contains uploaded files.
Final Answer:
A dictionary-like object containing uploaded files -> Option A
Quick Check:
Files = dictionary-like object [OK]
Hint: Remember: files come in a dictionary, not a list or string [OK]
Common Mistakes:
Confusing request.files with request.form
Expecting a list instead of a dictionary-like object
Thinking it automatically saves files
2. Which of the following is the correct way to check if a file was uploaded in Flask?
easy
A. if request.files.filename == ''
B. if 'file' in request.files and request.files['file'].filename != ''
C. if request.form['file'] != None
D. if request.files['file'] is None
Solution
Step 1: Check file presence in request.files
Use 'file' in request.files to confirm the file input exists.
Step 2: Verify filename is not empty
Check request.files['file'].filename != '' to ensure a file was selected.
Final Answer:
if 'file' in request.files and request.files['file'].filename != '' -> Option B
Quick Check:
Check key and filename not empty [OK]
Hint: Check key exists and filename is not empty string [OK]
C. It should use request.form instead of request.files
D. It uses an unsafe filename directly
Solution
Step 1: Identify filename safety issue
Using file.filename directly can allow unsafe paths or characters.
Step 2: Recommend using secure_filename
To avoid security risks, filenames must be sanitized before saving.
Final Answer:
It uses an unsafe filename directly -> Option D
Quick Check:
Always sanitize filenames before saving [OK]
Hint: Always use secure_filename before saving files [OK]
Common Mistakes:
Not checking if file exists before saving
Saving files without sanitizing filename
Confusing request.form with request.files
5. You want to allow users to upload only PNG images and save them safely in Flask. Which code snippet correctly implements this?
hard
A. file = request.files['image']
if file and file.filename.endswith('.png'):
filename = secure_filename(file.filename)
file.save(f"uploads/{filename}")
return 'PNG saved'
else:
return 'Invalid file'
B. file = request.files['image']
if file.filename:
file.save(file.filename)
return 'File saved'
else:
return 'No file'
C. file = request.files.get('image')
if file and file.filename:
filename = secure_filename(file.filename)
file.save(f"uploads/{filename}")
return 'File saved'
else:
return 'No file uploaded'
D. file = request.files['image']
if file and file.filename.endswith('.png'):
file.save(file.filename)
return 'PNG saved'
else:
return 'Invalid file'
Solution
Step 1: Check file presence and extension
file = request.files['image']
if file and file.filename.endswith('.png'):
filename = secure_filename(file.filename)
file.save(f"uploads/{filename}")
return 'PNG saved'
else:
return 'Invalid file' checks if file exists and filename ends with '.png' to allow only PNG files.
Step 2: Use secure_filename before saving
It sanitizes the filename to prevent security issues before saving.
Step 3: Return appropriate messages
Returns confirmation if saved, else an invalid file message.
Final Answer:
Option A correctly checks extension and uses secure_filename -> Option A
Quick Check:
Check extension + secure filename + save [OK]
Hint: Check extension and sanitize filename before saving [OK]
Common Mistakes:
Not sanitizing filename before saving
Not checking file extension properly
Saving files without checking if uploaded
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.