ajax 文件上传

在html中

<h3>ajax的文件上传</h3>


图片<input type="file" id="file" name="img">
<input type="submit" id="ajax-submit" value="ajax-上传">


{#<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>#}
<script src="/static/js/jquery-3.3.js"></script>
<script src="/static/js/ajax_setup.js"></script>   相当于给请求头加了一个csrftoken的值,然后通过中间件做校验
<script>
    // 注意的是页面中没有用到form表单,那么怎么提交数据呢,
    // 答案是用FormData来模拟表单中的<input type="file" id="file">

    $("#ajax-submit").click(function () {
        var form_obj = new FormData();  //文件上传 实例化一个空的FormData对象

        // 发ajax请求不需要csrf  ????  是因为上面引入了官方文档 所有不需要再写csrftoken了
        {#form_obj.append("csrfmiddlewaretoken",csrf); //给当前的FormData添加一个键值对#}

        //form_obj.append添加的键值对的名字***** 以这种形式添加的数据类型就相当于form表单中的 enctype="multipart/form-data" 所以processData不需要再做处理
        form_obj.append("img", $("[name='img']")[0].files[0]);  //转成dom对象之后,获取里面的单个文件
        {#form_obj.append("img",$("[name='img']")[0]// 把jq对象转成dom对象#}
        {#form_obj.append("img",$("[name='img']")[0].files //files表示获取里面的多个文件#}

        $.ajax({
            url: "/file_upload/",
            type: "post",

            // ajax 文件上传的必备参数
            processData: false,//不处理数据  不写的话会做urlencode处理
            contentType: false,//不设置内容类型
            data: form_obj,//发送一个FormData对象

            success: function (response) {
                alert(response)
            }

        })

    });


</script>

views视图中

def file_upload(request):
    if request.is_ajax(): #发 ajax请求
        file_obj=request.FILES.get("img")
        #拿html页面里给的form_obj.append("img", $("[name='img']")[0].files[0])里面的key值 img
        

     print(file_obj)#是个文件对象 file_name=file_obj.name path=os.path.join(settings.BASE_DIR,"media","img",file_name) with open(path,"wb") as f: for line in file_obj.chunks(): #大文件用chunks方法读 f.write(line)#写入文件 return HttpResponse("上传成功") return render(request,"file_upload.html")
原文地址:https://www.cnblogs.com/kenD/p/10127207.html