Reputation: 7228
I don't understand why but if I try to upload file via ajax it does not work but with regular request it does.
Printed the request.FILES.
#For ajax request
<MultiValueDict: {}>
#For regular request
<MultiValueDict: {u'file': [<TemporaryUploadedFile: IMG_3056.JPG (image/jpeg)>]}>
#Here's my front-end and back-end code
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
...
</form>
function submitForm(target, form){
$.ajax({
url:form.attr('action'),
type:'post',
data:form.serialize(),
dataType:"html",
error:function(data, status, xhr){
error();
},
beforeSend:function(){
loading();
},
success:function(data, status, xhr){
$(target).html(data);
},
complete:function(){
loadingDone();
}
});
}
#views.py
def file_upload(request):
doc_form = DocumentForm(user = request.user)
if request.method == 'POST':
doc_form = DocumentForm(request.POST, request.FILES, user = request.user)
print request.FILES
if doc_form.is_valid():
document = doc_form.save()
return render_to_response("create_doc.html", { 'doc_form':doc_form,
}, context_instance = template.RequestContext(request))
Upvotes: 1
Views: 1441
Reputation: 5256
Please try using this jquery form submit plugin, I think it will manage to send the FILE to the server like you need.
(It works for me for a PHP server side, no reason why it wont work for you too)
Upvotes: 1
Reputation: 966
Uploading files with regular jQuery's AJAX does not work. See some of these links for help:
http://www.nickdesteffen.com/blog/file-uploading-over-ajax-using-html5
How can I upload files asynchronously?
Sending multipart/formdata with jQuery.ajax
Basically there is a new API in HTML 5 for dealing with files or the old school way is using an iFrame/Flash. Personally I used Uploadify on a project a couple of months ago.
Upvotes: 3