我不明白为什么,但是如果我尝试通过 ajax 上传文件,它不起作用,但通过常规请求它可以。
打印 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))