Hi I’m quite new to flask and I want to upload a file using an ajax call to the server. As mentioned in the documentation, I added a file upload to the html as folows:
JavaScript
x
15
15
1
<form action="" method=post enctype="multipart/form-data" id="testid">
2
<table>
3
<tr>
4
<td>
5
<label>Upload</label>
6
</td>
7
<td>
8
<input id="upload_content_id" type="file" name="upload_file" multiple>
9
<input type="button" name="btn_uplpad" id="btn_upload_id" class="btn-upload" value="Upload"/>
10
11
</td>
12
</tr>
13
</table>
14
</form>
15
and I wrote the ajax handler as this
JavaScript
1
13
13
1
$(document).ready(function() {
2
$("#btn_upload_id" ).click(function() {
3
$.ajax({
4
type : "POST",
5
url : "/uploadajax",
6
cache: false,
7
async: false,
8
success : function (data) {},
9
error: function (XMLHttpRequest, textStatus, errorThrown) {}
10
});
11
});
12
});
13
I do not know how to get the uploaded file (not the name) from this
JavaScript
1
2
1
<input id="upload_content_id" type="file" name="upload_file" multiple>
2
and save the file in folder. I’m not quite sure how to read the file from handler which i have written:
JavaScript
1
5
1
@app.route('/uploadajax', methods = ['POST'])
2
def upldfile():
3
if request.method == 'POST':
4
file_val = request.files['file']
5
I will be grateful if anyone can help. Thank you in advance
Advertisement
Answer
To answer your question…
HTML:
JavaScript
1
10
10
1
<form id="upload-file" method="post" enctype="multipart/form-data">
2
<fieldset>
3
<label for="file">Select a file</label>
4
<input name="file" type="file">
5
</fieldset>
6
<fieldset>
7
<button id="upload-file-btn" type="button">Upload</button>
8
</fieldset>
9
</form>
10
JavaScript:
JavaScript
1
17
17
1
$(function() {
2
$('#upload-file-btn').click(function() {
3
var form_data = new FormData($('#upload-file')[0]);
4
$.ajax({
5
type: 'POST',
6
url: '/uploadajax',
7
data: form_data,
8
contentType: false,
9
cache: false,
10
processData: false,
11
success: function(data) {
12
console.log('Success!');
13
},
14
});
15
});
16
});
17
Now in your flask’s endpoint view function, you can access the file’s data via flask.request.files.
On a side note, forms are not tabular data, therefore they do not belong in a table. Instead, you should resort to an unordered list, or a definition list.