I want to be able to upload my file from javascript without using the typical HTML form so that the page doesn't have to refresh when uploading the file to python.
I have not had any success getting my file with request.files
.
I have tried two different versions, one using an HTML form and one without.
When trying out the one with the HTML form, the output from request.files
is an ImmutableMultiDict that looks like this ImmutableMultiDict([('file', <FileStorage: '^RUT.csv' ('text/csv')>)])
whilst according to my understanding, it is supposed to be a dictionary.
Here is the code:
<form method="POST" action="/get_dims" enctype="multipart/form-data" id="import_form">
<input type="file" name="file" accept=".csv" id="training_set_import" value="import training set"/>
<input type="submit" value="Submit">
</form>
@app.route("/get_dims", methods=["POST"])
def getDatasetDims():
file_n = request.files
print("Got it!")
print(file_n)
return "None"
The other, preferable method I have tried is with javascript using AJAX. When doing this, request.files
returns an empty ImmutableMultiDict that looks like this ImmutableMultiDict([])
. Here is my code for this:
$(function(){
$("#training_set_import").change(function(){
var file_name = $("#training_set_import").val();
var form = $("#training_set_import").form;
var data = new FormData(form);
if (file_name !== ""){
$.ajax({
type: "POST",
url:"/get_dims",
enctype: "multipart/form-data",
data: {"file": data},
cache: false,
processData: false,
contentType: false
});
}
});
});
The python code is the same.
So my question is, how can I implement the javascript version of this so that I can manupulate the uploaded csv in python ?