django项目中form表单和ajax的文件上传功能。

form表单文件上传

路由

# from表单上传
path('formupload/',apply.formupload,name='formupload/'),

方法

# form表单文件上传
def formupload(request):
    if request.method == 'POST':
        image_obj = request.FILES.get('headimg')
        print(image_obj)
        with open(settings.MEDIA_ROOT+'/'+image_obj.name,'wb') as f:
            for lin in image_obj:
                f.write(lin)
    return HttpResponse('ok')

前端html

<form action="/apply/formupload/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="headimg">
    <input type="submit" value="form表单上传">
</form>

上传成功示例

#ajax上传

路由

# ajax上传文件
path('ajaxupload/',apply.ajaxupload,name='ajaxupload/'),

方法

# ajax文件上传
def ajaxupload(request):
    if request.method == 'POST':
        image_obj = request.FILES.get('headimg')
        print(image_obj)
        with open(settings.MEDIA_ROOT + '/' + image_obj.name, 'wb') as f:
            for lin in image_obj:
                f.write(lin)
    return HttpResponse('ok')

前端html

<form>
            {% csrf_token %}
{#            <div>用户名:<input type="text" name="username" id="username"></div>#}
            <div>选择文件:<input type="file" name="headimg" id="headimg"></div>
            <div><input id="dosubmit" type="button" name="dosubmit" value="ajax上传"></div>
        </form>
{#    ajax上传#}
        <script>
            $(document).ready(function () {

                $("#dosubmit").click(function () {
                    var formdata = new FormData();
{#                    formdata.append("username", $("#username").val());#}
                    formdata.append("headimg", $("#headimg")[0].files[0]);
                    formdata.append("csrfmiddlewaretoken", "{{ csrf_token }}");
                    $.ajax({
                        url: "/apply/ajaxupload/",
                        type: "post",
                        data: formdata,
                        contentType: false,//enctype="multipart/form-data"
                        processData: false,//不需要转换数据类型,即不需要把传输的数据转为字符串
                        success: function (res) {
                            console.log(res)
                        }
                    });


                });


            })
        </script>

done。

原文地址:https://www.cnblogs.com/nmsghgnv/p/11385458.html