首页 > 其他分享 >Ajax上传文件Djano后台接收

Ajax上传文件Djano后台接收

时间:2023-03-25 21:11:06浏览次数:38  
标签:info name request Djano Ajax user file message 上传

模态框的编写

<!--按钮 -->
<input type="button" class="btn btn-primary change-password-button Avatar" value="更换头像"
                           style="margin-left: 40px">
    <!-- 更换头像模态框开始 -->
    <div class="modal fade" id="avatarModal" tabindex="-1" role="dialog" aria-labelledby="avatarModalLabel"
         aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header border-0">
                    <h5 class="modal-title text-white" id="avatarModalLabel">修改头像</h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body p-4">
                    <form id="Formadd" method="post" enctype="multipart/form-data">
                        {% csrf_token %}
                        <div class="form-group text-center">
                            <img id="image-preview" class="image-preview" src="#" alt="预览图片" style="display:none;">
                            <input type="file" name="avatarFile" class="form-control-file d-none" id="avatarFile">
                            <small class="form-text text-muted">建议尺寸为150x150像素,文件格式为JPG、PNG或GIF。</small>
                        </div>
                    </form>
                </div>
                <div class="modal-footer border-0">
                    <button type="button" class="btn btn-secondary rounded-pill" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary rounded-pill" id="saveAvatarBtn">保存</button>
                </div>
            </div>
        </div>
    </div>
    <!-- 模态框结束 -->

Ajax编写

function AvatarBtnEvent() {
            $(".Avatar").click(function () {

                $("#avatarModal").modal('show');
            });
        }


        function AvatarFormBtnEvent() {
            $("#saveAvatarBtn").click(function () {
                //创建文件对象 获取文件数据
                var form_data = new FormData();
                var file_info = $('#avatarFile')[0].files[0];
                form_data.append('myfile', file_info); //这里的myfile与视图中获取的request.FILES.get("myfile", None)要一致

                $.ajax({
                    url: "/userinfo/updataavatar/",  //
                    type: "post",
                    data: form_data,
                    contentType: false,
                    processData: false,
                    dataType: "JSON",
                    success: function (res) {
                        alert(res.message)
                        location.reload()
                    }
                })
            });
        }

Djano后台接收并写到数据库

def update_avatar(request):
    file_object = request.FILES.get("myfile")
    if request.method == 'POST' and file_object:
        # 打开文件对象并保存文件数据
        with open('media/user_images/' + file_object.name, 'wb+') as destination:
            for chunk in file_object.chunks():
                destination.write(chunk)
        # 修改用户数据库头像的路径
        user_image = os.path.join("user_images/", file_object.name)
        queyrset = models.UserInfo.objects.filter(name=request.session.get("info")["name"]).update(
            user_image=user_image)
        message = "更换成功"
        request.session["info"]["img"] = str(models.UserInfo.objects.filter(
            name=request.session.get("info")["name"]).first().user_image)
        return JsonResponse({'success': True,
                             "message": message
                             })
    message = "更换失败,请重试。"
    return JsonResponse({'success': False,
                         "message": message
                         })

标签:info,name,request,Djano,Ajax,user,file,message,上传
From: https://www.cnblogs.com/zxc3360655/p/17255599.html

相关文章