Created
July 8, 2021 09:57
-
-
Save EdoardoVignati/63e6d8ef20cb3cecb22b65ee668cc7be to your computer and use it in GitHub Desktop.
Read multipart form data from Flask
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What's the difference between:
request.files.get("field_name")
andrequest.files["field_name"]
Well the main differences lies in the value returned and the error raised.
request.files.get("field_name")
, just returns anNone
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.