This post looks promising, but I can't figure out what is blobFile
in the code? Where can I get this variable?
How to upload a file using jQuery.ajax and FormData
Extra question:
I assume that FormData
object contains data in ALL input fields including file input. But it seems not the case. Otherwise we don't need to append the file data to FormData
. Could anyone explain why file input is not included in the FormData
?
Also, I use Django backend, which by convention access uploaded files in request.FILES
. How can I put file data in request.FILES
rather than request.POST
with $.ajax()
?
EDIT
I just figured out that NOTHING is in my request.POST
and formData
in empty. can't figure out why.. Here is relevant code:
// html
<form action="" method="POST" enctype="multipart/form-data">{% csrf_token %}
<span class='file-name' id='file-name-1'>FILE 1</span>
<input type="file" id='id_image'>
<input class="browse-click" type="button" value="+"/>
<input id="send" type="submit" value="change">
</form>
// js
<script>
// when button is clicked, the file browser opens
$('.browse-click').on("click" , function () {
$('#id_image').click();
});
// upload file async when file is selected in file browser
$('#id_image').on('change', function () {
var currentpath = window.location.pathname;
var formData = new FormData($('form')[0]);
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
$.ajax({
url: currentpath, //server script to process data
type: 'POST',
xhr: function() { // custom xhr
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
</script>