因此,我尝试上传没有任何外部插件的文件,但是遇到了一些错误。
<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: {}>请求的文件。
<MultiValueDict: {}>
现在如何正确获取带有我的代码的上传文件?
我遵循了本教程http://www.script-tutorials.com/pure-html5-file- upload/,在php部分中,我替换为:
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 %}