zoukankan      html  css  js  c++  java
  • Django——三种方式上传文件/数据 (form ajax json)

    一、总结

    1.ajax上传文件

    1 http请求,body体中放文件内容,ajax本质就是发送http请求,所以它可以上传文件
    2 两种上传文件的方式,form表单,ajax
    
    3 固定模板
        var formdata=new FormData() 
        formdata.append('myfile',$("#id_file")[0].files[0])
        # 还可以带数据
        $.ajax({
                url:'/uploadfile/',
                method: 'post',
                //上传文件必须写这两句话
                processData:false,  # 预处理数据,
                contentType:false,  # 不指定编码,如果不写contentType,默认用urlencoded
                data:formdata,      # formdata内部指定了编码,并且自行处理数据
                success:function (data) {  
                    console.log(data)
                }
            })

    2.ajax提交json格式

    $.ajax({
                url:'/uploajson/',  //写全,是什么样就写什么样
                method:'post',
                contentType: 'application/json',
                //data要是json格式字符串
                //data:'{"name":"","password":""}',
                //把字典转成json格式字符串
                //JSON.stringify(dic)
                //把json格式字符串转成对象
                //JSON.parse(data)
                data:JSON.stringify({name:$("#id_name1").val(),password:$("#id_password1").val()}),
                success:function (data) {
                    //返回字符串类型,需要转成js的对象,字典
    
                    //1 如果:django 返回的是HttpResponse,data是json格式字符串,需要自行转成字典
                    //2 如果:django 返回的是JsonResponse,data是就是字典
                    //ajax这个方法做的是,如果响应数据是json格式,自动反序列化
                    console.log(typeof data)
                    var res=JSON.parse(data)
                    console.log(typeof res)
                    console.log(res.status)
                    console.log(res.msg)
    
    
                }
            })

    二、详解

    form表单文件/数据

    ajax上传文件/数据

    用ajax提交json格式数据

    index.html

    <head>
     <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js">
    </head>
    
    <body>
    <h1>form表单上传</h1>
    <form action="/uploadfile/" method="post" enctype="multipart/form-data">
        <p><input type="file" name="myfile"></p>
        <p>用户名:<input type="text" name="name"></p>
        <input type="submit" value="提交">
    </form>
    <hr>
    <h1>ajax上传</h1>
    <input type="file" id="id_file">
    <p>用户名:<input type="text" id="id_name"></p>
    <button id="btn_file">提交</button>
    <hr>
    <h1>通过ajax提交json格式数据</h1>
    
    <p>用户名:<input type="text" id="id_name1"></p>
    <p>密码:<input type="text" id="id_password1"></p>
    <p><button id="btn_json">提交</button></p>
    
    
    </body>
    <script>
        //使用原生js发送ajax请求(不讲,也不用看)
        //借助jquery封装好的ajax方法,发送ajax请求
        //点击button按钮,触发ajax请求
        $("#btn").click(function () {
    
            $.ajax({
                url: '/add/',  //向哪个地址发送请求
                method: 'post', //发送什么请求
                //使用jquery,获取输入框内的值
                //向后端传输的数据(没有指定编码,默认使用urlencoded)
                data: {'a': $("#first").val(), 'b': $("#second").val()},
                success: function (data) {
                    //数据正常返回,就会触发该匿名函数的执行,返回的数据就会复制给data
                    console.log(data)
                    //把后端返回的数据,通过dom操作,写到input框中
                    $('#result').val(data)
                },
                //请求失败,就会触发error的执行,并且把错误信息给error
                error: function (error) {
                    console.log(error)
    
                }
            })
    
    
        })
    
        //ajax上传文件
        $("#btn_file").click(function () {
            var formdata = new FormData() //实例化得到一个fromdata对象
            //把文件放到对象内
            //formdata.append('myfile',文件对象)
            formdata.append('myfile', $("#id_file")[0].files[0])
            //问题:fomdata现在只放了一个文件对象,可不可以放数据?可以
            //formdata.append('name','lqz')
            formdata.append('name', $("#id_name").val())
            $.ajax({
                url: '/uploadfile/',
                method: 'post',
                //上传文件必须写这两句话
                processData: false,
                contentType: false,
                data: formdata,
                success: function (data) {
                    alert(data)
                    //console.log(data)
                    //location.href='http://www.baidu.com'
    
                }
            })
        })
    
        //ajax提交json格式数据
        //ajax无法重定向,点击提交数据页面没有任何显示
        $("#btn_json").click(function () {
            $.ajax({
                url: '/uploadjson/',  //路径写准确,是什么样就写什么样,ajax无法重定向
                method: 'post',
                contentType: 'application/json',
                //data要是json格式字符串
                //data:'{"name":"","password":""}',
                //把字典转成json格式字符串
                //JSON.stringify(dic)
                //把json格式字符串转成对象
                //JSON.parse(data)
                data: JSON.stringify({name: $("#id_name1").val(), password: $("#id_password1").val()}),
                success: function (data) {
                    //返回字符串类型,需要转成js的对象,字典
    
                    //1 如果:django 返回的是HttpResponse,data是json格式字符串,需要自行转成字典
                    //2 如果:django 返回的是JsonResponse,data是就是字典
                    //ajax这个方法做的是,如果响应数据是json格式,自动反序列化
                    console.log(typeof data)
                    var res = JSON.parse(data)
                    console.log(typeof res)
                    console.log(res.status)
                    console.log(res.msg)
                }
            })
        })
    
    </script>

    views.py

    def uploadfile(request):
        file = request.FILES.get('myfile')
        # name = request.POST.get('name')
        # print(name)
        with open(file.name, 'wb') as f:
            for line in file:
                f.write(line)
        return HttpResponse('上传成功')
    
    from django.http import JsonResponse
    def uploadjson(request):
        data = request.body
        print(data)
        dic = {'status': 100, 'msg': '成功'}
    
        print(request.POST)  # 有数据?没有
        import json
    
        return HttpResponse(json.dumps(dic))#正常
        # return JsonResponse(dic)  # 报错,因为内部设置了默认编码,与需要不符

    url.py

    from django.urls import path
    from app01 import views
    urlpatterns = [
        # path('admin/', admin.site.urls),
        path('uploadfile/', views.uploadfile),
        path('uploadjson/', views.uploadjson),
    ]

    ps: 配置中可能遇到的问题

    settings.py

    1 注释中件件中# 'django.middleware.csrf.CsrfViewMiddleware',
    2 设置SLASH=False
    3 TEMPLATES 中配置 'DIRS': [os.path.join(BASE_DIR / 'templates')]
    4 配置static路径
    STATICFILES_DIRS=[
        os.path.join(BASE_DIR,'static')

    图示:

     

     

  • 相关阅读:
    sql语句中as的用法和作用
    设置国内AndriodSDK代理
    Ionic开发环境搭建
    SpringMvc+Mybatis开发调用存储过程
    SpringMvc的JSON数据交互
    SpringMvc+Mybatis开发需要的jar包
    nested exception is java.lang.NoClassDefFoundError: org/hibernate/validator/resourceloading/ResourceBundleLocator
    SpringMvc错误:HTTP Status 500
    解决在Tomcat中的server.xml中修改了配置,启动后还原的问题
    SpringMvc参数绑定出现乱码解决方法
  • 原文地址:https://www.cnblogs.com/guojieying/p/13838363.html
Copyright © 2011-2022 走看看