I'm doing multiple file upload with AJAX and DJango and I have problem.
How to get files from field input and push them to data
?
HTML:
<form id="add_photos" method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file[]" multiple id="files">
<input type="submit" name="submit" value="Submit" />
</form>
JS:
function formSubmit(e) {
e.preventDefault();
$.ajax({
method: 'POST',
data: form.serialize(),
url: '.',
success: function(data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
I'm doing multiple file upload with AJAX and DJango and I have problem.
How to get files from field input and push them to data
?
HTML:
<form id="add_photos" method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file[]" multiple id="files">
<input type="submit" name="submit" value="Submit" />
</form>
JS:
function formSubmit(e) {
e.preventDefault();
$.ajax({
method: 'POST',
data: form.serialize(),
url: '.',
success: function(data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
Share
Improve this question
asked Feb 16, 2018 at 14:40
CariwebCariweb
811 silver badge6 bronze badges
1 Answer
Reset to default 7See below an example using FormData
. But please note it may not work on old IE browsers (I think 8, 9 won't work).
<input type="file" id="upload_file" data-import-url="{% url 'upload_file' %}" data-csrf-token="{{ csrf_token }}" multiple>
Then the jQuery:
$("#upload_file").change(function () {
var url = $(this).attr("data-import-url")
var data = new FormData();
$.each($("#upload_file")[0].files, function(i, file) {
data.append("file", file);
});
data.append("csrfmiddlewaretoken", $(this).attr("data-csrf-token"));
$.ajax({
url: url,
data: data,
cache: false,
contentType: false,
processData: false,
type: 'post',
beforeSend: function () {
// before send, display loading, etc...
},
success: function (data) {
// success handling...
},
error: function () {
// error handling...
}
});
});
In your view you could get it like this:
uploaded_files = request.FILES.getlist('file')
If you need to support older browsers, the jQuery File Upload is a really good library. I've written a tutorial about multiple files upload using Django + Ajax (using this particular library).