I have a form with an input file and need to upload the file asynchronously to Django, but is not working with ajax. The code is as follows:
Form:
<form id="upload" method="post" action="/upload/" enctype="multipart/form-data">
<input type="file" name="test" id="test'>
<button type="submit">Upload</button></form>
JS:
function upload(event) {
event.preventDefault();
var data = new FormData();
data.append('upload',$('#test').prop('files')[0]);
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: data,
cache: false,
processData: false,
contentType: false,
success: function(data) {
alert('success');
}
});
return false;
}
$(function() {
$('form').submit(upload);
});
Django:
def upload(request):
print(request.FILES)
Django returns:
<MultiValueDict: {}>
Console JS:
console.log(data.get('upload'));
File { name: "test.csv", lastModified: 1446743198000, lastModifiedDate: Date 2015-11-05T17:06:38.000Z, size: 14, type: "text/csv" }
What am I doing wrong?