Reputation: 1293
I've trying to implement a file upload (a .csv
) with bootstrap, and submit it using a button.
I've tried alot of different ways of implementing the file upload and so far none of them work, I can't seem to pin point the issue:
<form method="POST" enctype="multipart/form-data" id="excel-upload" name="file">
<div class="file-upload-wrapper">
<label for="file">Upload Excel DAT File</label>
<input type="file" name="excel-upload-file" class="form-control-file" id="excel-upload-file">
<button class="btn btn-outline-success" type="button" id="submit_table" method="POST" style="margin-top: 30px">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true" id = "loading_spinner_table"></span>
Submit File
</button>
</div>
</form>
$("#submit_table").on('click', function(e) {
e.preventDefault();
$("#loading_spinner_table").show();
let form_data = new FormData($('#excel-upload-file')[0]);
console.log(form_data);
$.ajax({
url: "/upload_excel",
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log(data)
$("#loading_spinner_table").hide();
Plotly.plot('table_data',data);
},
error: function(result) {
$("#loading_spinner_table").hide();
alert("Invalid Submission / No Data");
}
});
});
@app.route('/upload_excel', methods=['POST', 'GET'])
def upload_blob():
if request.method in ('POST','GET'):
print(request.files)
if 'file' not in request.files:
print('NO FILE')
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
print('NOTHING SELECTED')
flash('No file selected for uploading')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
""" Additional processing"""
Upvotes: 1
Views: 301
Reputation: 10117
There are a couple changes that need to be made.
The FormData API needs to take a form, not a form element. Change the line where you build that object to this: let form_data = new FormData($('#excel-upload')[0]);
Next, your ajax call needs to specify that you're using multipart form encoding. Add this parameter to the call: enctype: 'multipart/form-data'
Third, the key for the file you want to use server side will match the name of the form element. In this case, you want to look for request.files['excel_upload_file']
It looks like this code is pulled from the flask file upload tutorial, so I'll assume you've set up flask to handle uploads already.
Upvotes: 1
Reputation: 245
We had same issue in MVC we changed button to **input type **submit**** then it worked. Button doesn't work work for form submit
Upvotes: 1