Consider this Flask route that handles a file upload and saves it:
from flask import Flask, request
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
file.save('/tmp/' + file.filename)
return 'File saved'What will happen if a user uploads a file named example.txt?
from flask import Flask, request app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] file.save('/tmp/' + file.filename) return 'File saved'
Look at the file.save line and the path used.
The file.save method saves the uploaded file to the path given. Here, it saves to /tmp/ plus the original filename, so the file will be saved as /tmp/example.txt.
Which of the following Flask code snippets correctly saves an uploaded file to the 'uploads' folder?
Remember that file.save() needs a full path including filename.
Option A correctly saves the file by combining the folder path and the filename. Options B and C miss the filename, causing errors. Option A tries to concatenate a file object, which is invalid.
Given this Flask route:
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
file.save('uploads/' + file.filename)
return 'Saved'When a user uploads a file, the server raises a FileNotFoundError. Why?
@app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] file.save('uploads/' + file.filename) return 'Saved'
Check if the folder path exists before saving files.
Flask's file.save() does not create directories. If the 'uploads' folder is missing, saving the file raises FileNotFoundError.
In Flask, after a user uploads a file named photo.png, what is the value of file.filename in this code?
file = request.files['file']
file = request.files['file']Think about what file.filename represents in Flask uploads.
The file.filename attribute contains the original name of the uploaded file, here 'photo.png'. It does not include the full path from the user's computer.
When saving uploaded files in Flask, how can you avoid overwriting existing files with the same name?
Think about how to keep filenames unique to avoid conflicts.
Using a UUID or timestamp to create a unique filename prevents overwriting existing files. Saving with original names risks conflicts. Overwriting loses data. Saving only in memory does not persist files.