如何使用Ajax在POST上上传文件?

时间:2021-06-13 19:43:35

I know the topics aren't missing on this subject that's why I looked into a huge amount of posts about this topic and couldn't find something that'd satisfy me, so I'm trying to build it by myself.

我知道在这个主题上没有遗漏的主题,这就是为什么我研究了大量关于这个主题的文章,却找不到让我满意的东西,所以我试图自己构建它。

All I want to do is to upload a file using Ajax with Django to avoid page refresh.

我要做的就是使用Django上传一个文件,以避免页面刷新。

Here's what I did :

以下是我所做的:

basic_upload.html :

basic_upload。html:

<form method="post" id="creationOptionsForm" enctype="multipart/form-data">
{% csrf_token %}

<div>
  {{ form.name.errors }}
  {{ form.name }}
</div>

<div>
  {{ form.email.errors }}
  {{ form.email }}
</div>

<div>
  {{ form.logo.errors }}
  {{ form.logo }}
</div>

<input type="submit" value="submit">
</form>

Ajax.js :

Ajax。js:

$(document).on('submit', '#creationOptionsForm', function(e){
  e.preventDefault();

  var form_data = new FormData();
  form_data.append('file', $('#creationOptionsForm').get(0).files);

  $.ajax({
      type:'POST',
      url:'/designer/results/',
      processData: false,
      contentType: false,
      data:{
          organisation:$('#id_organisation').val(),
          email:$('#id_email').val(),
          logo:form_data,
          csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
      },
  });
});

Views.py :

的观点。py:

def creationResult(request):
    if request.method == 'POST':
        form = UserInfos(request.POST, request.FILES)
        if form.is_valid():
            photo = form.save()
            ...
...

(forms.py & urls.py are correctly configured, it is not necessary to include them).

(形式。py和url。py是正确配置的,不需要包含它们)。

I guess there's an issue with the way I do on the ajax.js since on debug (pdb) request.POST return every datas except logo.

我想我在ajax上的做法有问题。从调试(pdb)请求开始。回传除logo外的所有数据。

What am I doing incorectly ?

我到底在做什么?

1 个解决方案

#1


10  

The below method works for me, it will submit all form value as serialize(). You will get all form input's inside request.POST and logo request.FILES

下面的方法适用于我,它将提交所有的表单值作为serialize()。您将获得所有表单输入的内部请求。邮报》和标志request.FILES

Try this:

试试这个:

$(document).on('submit', '#creationOptionsForm', function(e){
  e.preventDefault();

  var form_data = new FormData($('#creationOptionsForm')[0]);
  $.ajax({
      type:'POST',
      url:'/designer/results/',
      processData: false,
      contentType: false,
      async: false,
      cache: false,
      data : form_data,
      success: function(response){

      }
  });
});

Update:

更新:

basically async:false will do ajax request and stop executing further js code till the time request get complete, because upload file might take some time to upload to server.

基本上,async:false会执行ajax请求,在请求完成之前停止执行更多的js代码,因为上传文件可能需要一些时间才能上载到服务器。

While cache will force browser to not cache uploaded data to get updated data in ajax request

而缓存将迫使浏览器不缓存上传的数据以获得ajax请求中的更新数据

Official Documentation here

这里的官方文档

#1


10  

The below method works for me, it will submit all form value as serialize(). You will get all form input's inside request.POST and logo request.FILES

下面的方法适用于我,它将提交所有的表单值作为serialize()。您将获得所有表单输入的内部请求。邮报》和标志request.FILES

Try this:

试试这个:

$(document).on('submit', '#creationOptionsForm', function(e){
  e.preventDefault();

  var form_data = new FormData($('#creationOptionsForm')[0]);
  $.ajax({
      type:'POST',
      url:'/designer/results/',
      processData: false,
      contentType: false,
      async: false,
      cache: false,
      data : form_data,
      success: function(response){

      }
  });
});

Update:

更新:

basically async:false will do ajax request and stop executing further js code till the time request get complete, because upload file might take some time to upload to server.

基本上,async:false会执行ajax请求,在请求完成之前停止执行更多的js代码,因为上传文件可能需要一些时间才能上载到服务器。

While cache will force browser to not cache uploaded data to get updated data in ajax request

而缓存将迫使浏览器不缓存上传的数据以获得ajax请求中的更新数据

Official Documentation here

这里的官方文档