Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save EdoardoVignati/63e6d8ef20cb3cecb22b65ee668cc7be to your computer and use it in GitHub Desktop.
Save EdoardoVignati/63e6d8ef20cb3cecb22b65ee668cc7be to your computer and use it in GitHub Desktop.
Read multipart form data from Flask
from werkzeug.utils import secure_filename
from flask import Flask, render_template, request
@app.route("/my-upload-endpoint", methods=["POST"])
def my_upload_function():
if request.files.get("my-file-field-name") is None:
return render_template("my_error_page.html", an_optional_message="Error uploading file")
# Put here some other checks (security, file length etc...)
f = request.files["my-file-field-name"]
f.save(secure_filename(f.filename))
f.stream.seek(0)
content = ""
for line in f.stream.readlines():
content += line.decode("UTF-8") # Decode here as needed
print(content)
# <form action="/my-upload-endpoint" method="POST" enctype="multipart/form-data">
# <input name="my-file-field-name" type="file" class="form-control"/>
# <input type="submit" value="Upload">
# </form>
@u-m-i
Copy link

u-m-i commented Dec 28, 2024

What's the difference between:

request.files.get("field_name") and request.files["field_name"]

Well the main differences lies in the value returned and the error raised.

request.files.get("field_name"), just returns an None value but does not raise an error if the key is not found. We can also put a default value in case the key is not on the dictionary: request.files.get("field_name", -1). So it can be easier to check for inconsistency on the request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment