jquery - 通过 AJAX 发送图像文件。 request.FILES 为空?

标签 jquery ajax django http post

我正在尝试使用 Ajax 发送图像数据。但是我在后端得到的 request.FILES 是空的。我已将 multipart/form-data 添加到我的表单中,方法为 POST

这是我的 AJAX 调用:

 $(document).on('submit', '#profile_edit_form', function(event){

  event.preventDefault();


  $.ajax({
      url     : "/users/update_profile_info/",
      type    : 'post',
      dataType: 'json',
      data    : $(this).serialize(),
      success : function(data) {

        $('#profile_name_tag').html(data.username);
        $('#username_navbar').html(data.username);

        //SENDING THE IMAGE VIA AJAX HERE
        var img_data = $('#id_image').get(0).files;
        formdata = new FormData();
        formdata.append("img_data", img_data);

        $.ajax({
            url         : "/users/update_profile_image/",
            type        : 'POST',
            enctype     : "multipart/form-data",
            data        : formdata,
            cache       : false,
            contentType : false,
            processData : false,
            success : function(data) {
              console.log('success');
              //$('#profile_picture').html(data.)

            },
            error: function(data) {
              console.log('fail');
            }
        });

      },
      error: function(data) {
          console.log('fail');
      }
  });


});

这是我的表格:

   <form id="profile_edit_form" method="POST">
     {% csrf_token %}
     <fieldset class="form-group">
       <legend class="border-bottom mb4"> Profile Info </legend>
             {{u_form|crispy}}
            {{p_form|crispy}}
     </fieldset>
     <button class="btn btn-outline-info" type="submit"> Update Info </button>
   </form>

正如你所看到的,我使用的是 cispy 表单。图像字段位于 p_form

这是我的 django View

@login_required
def update_profile_image(request):
    print(not request.FILES)

    if request.method == 'POST':
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user)
        if p_form.is_valid():
            p_form.save()

            context = {'None': 'none'}
            return JsonResponse(context)
        else:
            return HttpResponse('None')

print(not request.FILES) 返回 True,图像当然不会上传。

我查过很多类似的问题。但在所有这些中,解决方案是将 multipart/form-data 添加到我已经完成的表单中。 那么有什么想法问题出在哪里吗?

谢谢!

最佳答案

我将代码更改为

var img_data = $('#id_image').get(0).files[0];
formdata = new FormData();
formdata.append("img_data", img_data);
//console.log(formdata.get("img_data"));

$.ajax({
    url         : "/users/update_profile_image/",
    type        : 'POST',
    //enctype     : "multipart/form-data",   //it is done inside jquery
    data        : formdata,
    cache       : false,
    contentType : false,
    processData : false,
    success : function(data) {
      console.log('success');
      //$('#profile_picture').html(data.)

    },
    error: function(data) {
      console.log('image-fail');
    }
});

终于成功了!

关于jquery - 通过 AJAX 发送图像文件。 request.FILES 为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52858520/

相关文章:

ajax - jsGrid 调用 Controller .Net Core - 单元格未加载数据

jquery - 使用 JQuery 解析此 JSON

python - django 使用外键连接

jquery - 如何隐藏 Twitter Bootstrap 下拉菜单

jquery切换事件来更改图像src

javascript - 使用 AJAX 调用恢复 session

python - 如何在 Django 记录器中获取应用程序名称

python - Django 联系表单确认电子邮件

javascript - 将变量作为输入传递给 Date.UTC

jquery - Safari 中的 html5 播放器控件太长