zoukankan      html  css  js  c++  java
  • form表单及ajax上传示例以及中间件的转换

    一.form表单上传文件

    渲染:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
         <script src="/static/jquery-3.3.1.js"></script>
    </head>
    <body>
    <h1>form_up</h1>
    <form action="" method="post" enctype="multipart/form-data">
        <input type="text" name="username">
        <input type="file" name="my_file">
        <input type="submit">
    </form>
    
    </body>
    </html>

    后台:

    def form_up(request):
        if request.method == 'POST':
            print(request.POST)
            import copy
            params = copy.deepcopy(request.POST)
            params["firstname"] = "zhao"
            print(params)
            request.POST = params
    #可利用深拷贝在POST中手动添加键值对
    #https://www.cnblogs.com/zgf-666/p/9161910.html
    print(request.POST) name = request.POST.get('firstname') print(name) print(type(name)) print(request.FILES) file_obj = request.FILES.get('my_file') print(file_obj.name) with open(file_obj.name,'wb') as f: for line in file_obj.chunks(): f.write(line) return HttpResponse('OK') return render(request,'form_up.html')

    二.ajax上传json数据

         渲染:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
         <script src="/static/jquery-3.3.1.js"></script>
    </head>
    <body>
        <button  id="d1">click me!</button>
    </body>
    <script>
                $('#d1').click(function () {
                       $.ajax({
                           url:'',  // url参数可以不写,默认就是当前页面打开的地址
                           type:'post',
                           contentType:'application/json',
                           data:JSON.stringify({'name':'jason','hobby':'study'}),
                           success:function (data) {
                                alert(data)
                           }
                       })
                    })
    </script>
    </html>

           后台:

    import json
    from django.http import JsonResponse
    def ajax_json(request):
        if request.method == 'POST':
            print(request.body)  # json格式只有通过request.body才能查看
            res = json.loads(request.body.decode('utf-8'))
            hobby = res.get('hobby')
    
            return HttpResponse('OK')  # 必须返回HttpResponse对象
        return render(request, 'ajax_json.html')

    三.通过ajax上传文件

          渲染:

    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
    <script src="/static/jquery-3.3.1.js"></script>
    
    
    
    <input type="file" name="myfile" id="i1">
    <button id="d1">提交~</button>
    
    
    <script>
            $('#d1').click(function () {
                       var formdata = new FormData();
                       // FormData对象不仅仅可以传文件还可以传普通的键值对
                        formdata.append('name','jason');
                        // 获取input框存放的文件
                        //$('#i1')[0]由Jquery对象变为js对象
                        formdata.append('myfile',$('#i1')[0].files[0]);
                        $.ajax({
                            url:'',
                            type:'post',
                            data:formdata,
                            // ajax发送文件需要修改两个固定的参数
                            processData:false,  // 告诉浏览器不要处理我的数据
                            contentType:false,  // 不要用任何的编码,就用我formdata自带的编码格式,django能够自动识别改formdata对象
                            // 回调函数
                            success:function (data) {
                                alert(data)
                            }
                        })
                    })
    </script>

    后台:

    def ajax_up(request):
            if request.method == 'POST':
                print(request.POST)  # 普通的键值对:<QueryDict: {'name': ['jason']}>
                print(request.FILES)
                # 传文件< MultiValueDict: {'myfile': [ < InMemoryUploadedFile: day17课件.md(application / octet - stream) >]} >
                file_obj = request.FILES.get('myfile')
                with open(file_obj.name, 'wb') as f:
                    for line in file_obj.chunks():
                        f.write(line)
                return HttpResponse('OK')
            return render(request, 'ajax_up.html')

    四.中间件将jason格式数据转换到request.POST字典中

        中间件:

    from django.utils.deprecation import MiddlewareMixin
    import json
    
    
    class MyMiddleWare(MiddlewareMixin):
        def process_request(self,request):
            print('我是第一个自定义的中间件中process_request方法')
            import copy
            params = copy.deepcopy(request.POST)
            # params["firstname"] = "zhao"
            # print(params)
            # request.POST = params
            if not request.POST:
                if request.body:
                    # < QueryDict: {'username': ['dasdas']} >
                    res = json.loads(request.body.decode('utf-8'))
                    print(res,type(res))
                    for k,v in res.items():
                        params[k] = v
                    request.POST = params
                    # print(request.POST)
    
    
        def process_response(self,request,response):
            print('我是第一个自定义的中间件中process_response方法')
            return response

      后台(form表单和ajax_jason数据都能正常通过request.POST取出):

    def ajax_json(request):
        if request.method == 'POST':
            # print(request.body)  # json格式只有通过request.body才能查看
            # res = json.loads(request.body.decode('utf-8'))
            # hobby = res.get('hobby')
            print(request.POST.get('hobby'))
            print(request.POST.get('name'))
            return HttpResponse('OK')  # 必须返回HttpResponse对象
        return render(request, 'ajax_json.html')
  • 相关阅读:
    WPF线程中获取控件的值和给控件赋值
    sublime text3 安装以及主要插件安装
    云服务IaaS,PaaS,SaaS
    What is JSON
    Core Java
    英语单词及语义
    设置PyCharm创建文件时自动添加头文件
    【练习】字典的循环遍历:实现多层级节点存取
    字符串格式化
    常用数据类型的方法--str、int、list、dict
  • 原文地址:https://www.cnblogs.com/sima-3/p/11390011.html
Copyright © 2011-2022 走看看