如何保存使用ajax在POST请求中获得的图像?

时间:2019-03-31 19:26:49

标签: javascript jquery ajax django

我是Django的新手。我创建了一个用于识别的表单,其中包含两个用于上传图片的字段-main_photo,profile_photo

我有一个上传图像的Django表单。在ajax FormData()的帮助下(我正在与她打交道,也许),我通过POST request将它们发送给函数。但是我不能存储它们。救救我。

模板

<input type="hidden" name="csrfmiddlewaretoken" value="9S6oPbkHujBnxaKHSxzU5W4mdkEs6Lbbf3g0OIJAk3lBfaMV8bafzpz8QudIuofJ">
  9S6oPbkHujBnxaKHSxzU5W4mdkEs6Lbbf3g0OIJAk3lBfaMV8bafzpz8QudIuofJ
    <div class="field inline">
        <div class="subhead"></div>

        <input type="file" name="main_photo" required="" id="id_main_photo">
        <label for="foto1" class="id_foto">
            <div class="addPhoto">
                <div class="button"></div>
            </div>
        </label>
    </div>
    <div class="field inline">
        <div class="subhead"></div>
        <input type="file" name="profile_photo" required="" id="id_profile_photo">
        <label for="foto2" class="id_foto">
            <div class="addPhoto">
                <div class="button"></div>
            </div>
        </label>
    </div>
    <div class="center">
      <button class="submit mgln" type="button"></button>
    </div>

jquery

var token = '{{csrf_token}}';
$('.mgln').on('click', function(){

    photo = new FormData();
    photo.append('file1', $('input[name=main_photo]').prop('files')[0])
    photo.append('file2', $('input[name=profile_photo]').prop('files')[0])
    photo1 = photo.getAll('file1')
    photo2 = photo.getAll('file1')
  data = {
      photo1: photo1,
      photo2: photo2,
    }
    console.log(data)
    $.ajax({
      headers: { "X-CSRFToken": token },
      type: "POST",
      url: "{% url 'identification_view' %}",
      data: data,
      processData: false,
      contentType: false,
      success: function(result) {
        alert('Ok.');
      },
      error: function(result) {
        alert('Error.');
      }
    })
  })

观看次数

def identification_view(request):
    if request.method == 'POST':
        form = IdentificationForm(request.POST, request.FILES)
        if request.is_ajax():
            print(request.POST.values())      #[]
            print(request.FILES.values())     #[]
            return HttpResponse('image upload success')
    else:
        form = IdentificationForm()
    identifications  = RequestUser.objects.filter(user = request.user)

    return render(request, 'accounts/identification.html', {'form': form, 'identifications': identifications})

表格

class IdentificationForm(forms.ModelForm):
    class Meta:
        model = RequestUser
        fields = ('main_photo', 'profile_photo', )

    def clean_image(self):
        ...

    def clean_image2(self):
        ...

1 个答案:

答案 0 :(得分:0)

视图

def identification_view(request):
    if request.method == 'POST':
        form = IdentificationForm(request.POST, request.FILES)
        if request.is_ajax():
            print(dir(request.FILES))
            main_photo = request.FILES.get('file1')
            profile_photo = request.FILES.get('file2')
            RequestUser.objects.create(
            user = request.user,
            main_photo = main_photo,
            profile_photo = profile_photo
            )
            return HttpResponse('image upload success')
    else:
        form = IdentificationForm()
    identifications  = RequestUser.objects.filter(user = request.user)

    return render(request, 'accounts/identification.html', {'form': form, 'identifications': identifications})

脚本

var token = '{{csrf_token}}';
$('.mgln').on('click', function(){
    formData = new FormData();
    formData.append('file1', $('input[name=main_photo]')[0].files[0])
    formData.append('file2', $('input[name=profile_photo]')[0].files[0])
    $.ajax({
      headers: { "X-CSRFToken": token },
      type: "POST",
      url: "{% url 'identification_view' %}",
      data: formData,
      processData: false,
      contentType: false,
      success: function(result) {
        alert('ok.');
      },
      error: function(result) {
        alert('error.');
      }
    })
  })