jquery – Django ajax文件上传

前端之家收集整理的这篇文章主要介绍了jquery – Django ajax文件上传前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我试图上传一个没有任何外部插件文件,但我遇到了一些错误.
<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>

我的服务器:@H_403_5@

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:{}>对于request.FILES@H_403_5@

如何使用我的代码正确获取上传文件?@H_403_5@

解决方法

这是我使用javascript上传文件内容,希望这有帮助!只需将$(‘#file’)作为参数传递即可.
function upload(field,upload_url) {
    if (field.files.length == 0) {
        return;
    }
    file = field.files[0];
    var formdata = new FormData();
    formdata.append('file_upload',file);
    $.ajax({
        url: upload_url,data: formdata,processData: false,contentType: false,success: console.log('success!')
    });
}

[编辑]@H_403_5@

这就是我在服务器端所做的事情(简化):@H_403_5@

def save_file(dest_path,f,filename):
    original_name,file_extension = os.path.splitext(f.name)
    filename = filename + '-' + datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + file_extension
    url = '/' + dest_path + '/' + filename
    path = django_settings.MEDIA_ROOT + url
    destination = open(path,'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()
    return path

class FileUploadView(View):
    def post(self,**kwargs):
        if request.FILES and request.FILES.get('file_upload'):
            path = save_file(UPLOAD_TO,request.FILES.get('file_upload'),FILENAME)
        return self.render_to_response({})
原文链接:https://www.f2er.com/jquery/181478.html

猜你在找的jQuery相关文章