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

时间:2018-10-17 15:28:41

标签: 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>

如您所见,我使用的是顺式表格。图片字段位于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。 那么问题出在哪里呢?

谢谢!

2 个答案:

答案 0 :(得分:1)

当您期望单个实体时,您将向GalleryActivity --> ViewPager --> TabFragment --> GalleryFragment --> RecyclerView --> ImageView (file path will go one level deeper by replacing GalleryFragment when a folder is clicked) SlideshowActivity --> ViewPager --> SlideshowFragment --> ImageView 提供整个files集合。

尝试仅从FormData.append()访问单个文件,然后传递该文件:

files

我还建议删除var img_data = $('#id_image').get(0).files[0]; // note [0] 设置,因为当您向请求提供enctype对象时,jQuery会自动为您执行此操作。手动设置该值可能会覆盖不正确的值。

答案 1 :(得分:0)

我将代码更改为

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');
    }
});

它终于奏效了!