I'm trying to read a form containing an uploaded file in form with Flask 0.11.1 in Python 2.7.6.
app.route("/registration_submission")
def registration_submission():
print request.files
print request.form
print request.data
# sth else...
Several methods I have tried give following results:
(1) Pure HTML form. It is like the following. The name field is contained according to the W3S Note, and the enctype is set to multipart/form-data:
<form id="register-form" action="/registration_submission" method="post" enctype="multipart/form-data">
<div><input type="text"id="firstname" name="firstname"></div>
<div><input type="text"id="lastname" name="lastname"></div>
<div><input type="file" id="resume" name="resume"></div>
<button type="submit" id="send">Submit</button>
</form>
- The file can be retrieved from
request.form['filename'] request.datais empty. It is usually empty according to this and this.
(2) jQuery AJAX POST. In addition to the HTML form used above, I set AJAX processData to false.
$.ajax({
type: "POST",
url: "/registration_submission",
data: submission_data,
processData: false,
error: function(response, error) {
;
},
success: function(data, code, jqxhr) {
;
}
});
- If the
submission_datawas acquired byvar submission_data = $('#form').serialize()then:request.filesis emptyrequest.formcontains all other information except the uploaded file, in pretty formatrequest.datais empty. But if I call it after callingrequest.get_data()then request.data is a nicely formatted url-style string
- If, however, I use
var submission_data = new FormData($('#form')[0])then:request.filesis emptyrequest.formcontains a messy blurb of encoded charactersrequest.form.to_dict()returns a dictionary of a messy blurbrequest.datais empty. If I look forrequest.dataafter callingrequest.get_data()then it seems likerequest.datacontains several thousand lines of information containing almost the whole html page.
Any idea to make jQuery AJAX form containing file and data retrievable in Flask? (I can't use option (1) since I need to do some checking before submitting the form). Thanks!