Django ajax文件上传 [英] Django ajax file upload
本文介绍了Django ajax文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我试图上传没有任何外部插件的文件,但是我遇到一些错误。
So I am trying to upload a file without any external plugins, but I am running into some errors.
<form method="" action="" name='upload_form' id='upload_form' >
{% csrf_token %}
<input type='file' name='file' id='file' />
<input type='button' value='Upload' id='upload'/>
</form>
<script type='text/javascript'>
$(document).ready(function() {
var csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
$('#upload').click(function() {
$.ajax({
csrfmiddlewaretoken: csrf_token,
type: 'POST',
url : 'upload',
enctype: "multipart/form-data",
data : {
'file': $('#file').val()
},
success: function(data) {
console.log(data)
}
})
})
})
</script>
我的服务器:
class ImageUploadView(LoginRequiredMixin, JSONResponseMixin, AjaxResponseMixin, CurrentUserIdMixin, View):
@method_decorator(csrf_protect)
def dispatch(self, *args, **kwargs):
return super(ImageUploadView, self).dispatch(*args, **kwargs)
def post_ajax(self, request, username):
print request.POST.get('file', None)
print request.FILES
# id = request.POST['id']
# path = 'pictures/'
# f = request.FILES['picture']
# destination = open(path, 'wb+')
# for chunk in f.chunks():
# destination.write(chunk)
# destination.close()
return HttpResponse("image uploaded")
我得到一个< MultiValueDict:{}>
的请求.FILES
I get a <MultiValueDict: {}>
for the request.FILES
如何正确获取上传的文件现在用我的代码?
how do I properly get the uploaded file now with my code?
推荐答案
我遵循本教程 http://www.script-tutorials.com/pure-html5-file-upload/ ,在php部分我替换为:
i followed this tutorial http://www.script-tutorials.com/pure-html5-file-upload/ and in the php part i replaced with :
class UploadImageView(LoginRequiredMixin, CurrentUserIdMixin, View):
@method_decorator(csrf_protect)
def dispatch(self, *args, **kwargs):
return super(UploadImageView, self).dispatch(*args, **kwargs)
def post(self, request, username):
path = 'myproject/media/pictures/guitar.jpg'
f = request.FILES['image_file']
destination = open(path, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
return HttpResponse("image uploaded")
也更改了这一行
<form id="upload_form" enctype="multipart/form-data" method="post" action=".">
{% csrf_token %}
这篇关于Django ajax文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文