Serving uploaded files lets users access files they have sent to your app. It makes the files available through a web link.
Serving uploaded files in Flask
from flask import send_from_directory @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory('uploads', filename)
send_from_directory safely sends files from a folder.
The folder name is relative to your app's root folder.
user_uploads. It supports subfolders because of path:filename.from flask import send_from_directory @app.route('/files/<path:filename>') def serve_file(filename): return send_from_directory('user_uploads', filename)
static/images folder.from flask import send_from_directory @app.route('/images/<filename>') def serve_image(filename): return send_from_directory('static/images', filename)
This Flask app lets users upload a file via a form. After uploading, it saves the file in the uploads folder. Then it redirects the user to a URL where the uploaded file is served back using send_from_directory.
This way, users can upload and then view or download their files easily.
from flask import Flask, request, redirect, url_for, send_from_directory import os app = Flask(__name__) UPLOAD_FOLDER = 'uploads' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER os.makedirs(UPLOAD_FOLDER, exist_ok=True) @app.route('/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': file = request.files.get('file') if file: filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename) file.save(filepath) return redirect(url_for('uploaded_file', filename=file.filename)) return ''' <h1>Upload a file</h1> <form method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form> ''' @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) if __name__ == '__main__': app.run(debug=True)
Always validate and sanitize filenames to avoid security risks.
Use send_from_directory instead of send_file for safer file serving.
Make sure the upload folder exists and has correct permissions.
Use send_from_directory to serve uploaded files safely.
Set up a route that takes a filename and returns the file from your upload folder.
After uploading, redirect users to the file URL to access their files.
Practice
Solution
Step 1: Understand serving files in Flask
Flask provides a function specifically to serve files from a folder safely, which issend_from_directory.Step 2: Identify the correct function
render_templateis for HTML templates,redirectsends users to a different URL, andurl_forbuilds URLs. Onlysend_from_directoryserves files.Final Answer:
send_from_directory -> Option AQuick Check:
Serving files = send_from_directory [OK]
- Confusing send_from_directory with render_template
- Trying to serve files with redirect
- Using url_for to serve files directly
example.txt from the folder uploads in Flask?Solution
Step 1: Recall the function signature
send_from_directorytakes two arguments: the folder name and the filename.Step 2: Match the syntax
send_from_directory('uploads', 'example.txt') correctly callssend_from_directory('uploads', 'example.txt'). Options A, B, and D use incorrect functions or formats.Final Answer:
send_from_directory('uploads', 'example.txt') -> Option CQuick Check:
Correct syntax = send_from_directory(folder, filename) [OK]
- Using send_file with folder and filename as one string
- Using redirect to serve files
- Using url_for incorrectly for file serving
from flask import Flask, send_from_directory
app = Flask(__name__)
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory('uploads', filename)What happens when a user visits
/uploads/photo.png?Solution
Step 1: Analyze the route and function
The route captures the filename from the URL and callssend_from_directorywith 'uploads' folder and the filename.Step 2: Understand the behavior on URL visit
Visiting/uploads/photo.pngtriggers the function to send the file 'photo.png' from the 'uploads' folder to the user.Final Answer:
The file 'photo.png' is sent from the 'uploads' folder to the user. -> Option DQuick Check:
Route sends file from folder = The file 'photo.png' is sent from the 'uploads' folder to the user. [OK]
- Assuming route returns text instead of file
- Thinking route redirects instead of serving file
- Believing route is invalid and causes 404
from flask import Flask, send_from_directory
app = Flask(__name__)
@app.route('/files/<filename>')
def files(filename):
return send_from_directory(filename, 'uploads')Solution
Step 1: Check send_from_directory arguments
The function call usessend_from_directory(filename, 'uploads'), but the first argument should be the folder, second the filename.Step 2: Confirm correct argument order
The correct call issend_from_directory('uploads', filename). The route and function name are valid, and send_from_directory is allowed in routes.Final Answer:
The folder and filename arguments are reversed in send_from_directory. -> Option AQuick Check:
send_from_directory(folder, filename) order matters [OK]
- Swapping folder and filename arguments
- Thinking function names like 'files' are reserved
- Believing send_from_directory can't be used in routes
user_uploads. Which Flask route setup correctly serves files while preventing directory traversal attacks?Solution
Step 1: Understand directory traversal risks
Allowingpath:filenamelets users include slashes, risking access outside the folder.Step 2: Choose safe route and function
@app.route('/files/<filename>') def serve_file(filename): return send_from_directory('user_uploads', filename)uses<filename>(no slashes) andsend_from_directory, which safely serves files and prevents traversal.Step 3: Evaluate other options
@app.route('/files/<path:filename>') def serve_file(filename): return send_from_directory('user_uploads', filename)allows paths, risking traversal.@app.route('/files/<filename>') def serve_file(filename): return send_file(f'user_uploads/{filename}')usessend_filewith string path, less safe.@app.route('/files/<filename>') def serve_file(filename): return open(f'user_uploads/{filename}').read()reads file content directly, unsafe and breaks response.Final Answer:
Route with <filename> and send_from_directory for safe serving -> Option BQuick Check:
Use send_from_directory with filename only to prevent traversal [OK]
- Using allowing directory traversal
- Using send_file with raw paths risking security
- Reading file content directly instead of sending file
Ready to prove it?
Pass the test and this pattern moves unknown
