Reputation: 20349
I want to post a csv file to django view using jquery
<form id="form" enctype="multipart/form-data" >
<input type="file" name="ListFile" id="ListFile" />
<button type="button" onclick="csv_send">upload</button>
</form><br>
js is:
function csv_send(){
var data = {
'csrfmiddlewaretoken' : $('input[name=csrfmiddlewaretoken]').val(),
'data': $("#ListFile").val()
}
/*$.ajax({
type: 'POST',
url:'/list/create/',
cache:false,
dataType:'json',
data:data,
success: function(result) {
console.log("ok")
}
});*/
}
django views.py:
def createlist(request):
if request.method == 'POST':
file = request.FILES
here not getting file.
I know getting file using form action.But here i want to post file through javascript because i want response back to javascript after success.
Clearly i want that file in views.py by request.FILES
Upvotes: 0
Views: 952
Reputation: 74
You have to use a FormData object and a slightly modified version of basic ajax post:
var data = new FormData();
var file = null;
//when uploading a file take the file
$("#your-file-input-id").on("change", function(){
file = this.files[0]
});
//append the file in the data
data.append("file", file);
//append other data
data.append("message", "some content");
$.ajax({
url: '/path',
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function (data, status, xhr) {
//handle success },
error: function (data, status, xhr) {
//handle error
}
});
In Django you will find the file in request.FILES['file']. I hope this is helpful.
Upvotes: 0
Reputation: 113
When uploading files, your form must have this attribute:
enctype='multipart/form-data'
like this:
<form id="form" enctype='multipart/form-data'>
This might help you understand.
Upvotes: 1