Reputation: 151
So I have an HTML form with a few input text fields, but now I want to include file uploading in the same form as well.
I saw in other posts in here that using a FormData object would do the job for me. However when I implement it the dict that I receive in Flask is empty.
Here is the HTML form. The button that calls the action is outside the form - I handle it with Ajax as I don't want to refresh the page.
<form action="{{ url_for('configure') }}" method="post" enctype="multiform/form-data" id="form_withtabs">
<div class="row">
<br>
<div class="col-lg-2">
<label>
<input type="text" id="input_username" name="username" class"form-control" placeholder="Username" >
</label>
</div>
<div class="col-lg-2">
<label>
<input type="password" name="password" class"form-control" placeholder="Password" />
</label>
</div>
<div class="col-lg-3">
<input class="pull-right" type="text" name="project_name" data-toggle="tooltip" data-placement="left" title="Select a name for the project" placeholder="Project Name" />
</div>
<div class="col-lg-5">
<input type="file" name="config_file" class="pull-right" />
</div>
</div>
</form>
var thisformData = new FormData($('#form_withtabs'));
$.ajax({
url: "/configure",
data: thisformData,
type: 'POST',
contentType: false,
cache: false,
processData: false,
async: false,
success: function(response) {
var $link_addr = $(response).filter('#link').html();
$('body').removeClass("loading");
$(".alert-danger").html($link_addr);
$(".alert-danger").show();
return true;
}
And this is the function that handles the request.
@app.route('/configure', methods=['POST'])
def configure():
print request.form
if request.method == 'POST':
#request the file from
file = request.files['config_file']
if file:
filename = secure_filename(file.filename)
#app.config["UPLOAD_FOLDER"] is defined in flask_define.py
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
The result that I get from pressing submit is
ImmutableMultiDict([])
And 400 Bad Request
Can somebody help me find my mistake?
Upvotes: 2
Views: 1054
Reputation: 151
I found the solution.
Instead of using var thisformData = new FormData($('#form_withtabs'));
I tried using var form = document.querySelector('#form_withtabs');
var formData = new FormData(form);
At the end that solved my problem and Flask now receives everything.
Upvotes: 1