简体   繁体   English

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

[英]How to upload a file using Ajax on POST?

I know, the topics aren't missing on this subject but bear with me. 我知道,关于这个主题的话题并非没有,但请耐心等待。 I'd like to upload a file to the server using Ajax or an equivalent. 我想使用Ajax或等效文件将文件上传到服务器。

# html
<form method="post" id="Form" enctype="multipart/form-data">
  {% csrf_token %} # django security
  <input id="image_file" type="file" name="image_file">
  <input type="submit" value="submit">
</form>

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

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

  $.ajax({
      type:'POST',
      url:'my_url',
      processData: false,
      contentType: false,
      data:{
          logo:form_data,
          csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), # django security
      },
  });
});

# views.py (server side)
def myFunction(request):
    if request.method == 'POST':
        image_file = request.FILES
        ...
...

I guess there's an issue with the way I configured the ajax function since on debug mode, every data are returned except the logo . 我猜我配置ajax函数的方式存在问题,因为在调试模式下,除logo之外的所有数据都将返回。

Am I doing something incorrectly? 我做错了什么吗?

The below method works for me, it will submit all form value as serialize() . 下面的方法对我有用,它将所有表单值提交为serialize() You will get all form input's inside request.POST and logo request.FILES 您将获得所有表单输入的内部request.POST和徽标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 虽然cache将强制浏览器不缓存上传的数据以获取ajax请求中的更新数据

Official Documentation here 官方文件在这里

Looking back, the older answer is unpractical and not recommended. 往回看,较旧的答案不切实际,不建议使用。 asnyc: false pauses the entire Javascript to simply upload a file, you are likely firing other functions during the upload . asnyc: false暂停整个Javascript以仅上传文件, 您可能会在上传过程中触发其他功能

If you are using JQuery solely for the use of ajax , then I recommand using axios : 如果您仅将JQuery用于ajax的使用,那么我建议使用axios

const axios = require('axios');

var formData = new FormData();
formData.append('imageFile', document.querySelector('#image_file').files[0]);

axios({
    method: 'post',
    url: 'your_url',
    data: formData,
    headers: {
        "X-CSRFToken": CSRF_TOKEN, # django security
        "content-type": "multipart/form-data"
    }
}).then(function (response) {
    # success
});

Axios Documentation Axios文档


Jquery/Ajax answer: jQuery / Ajax答案:

var formData = new FormData();
formData.append('imageFile', $('#image_file')[0].files[0]);
formData.append('csrfmiddlewaretoken', CSRF_TOKEN); # django security

$.ajax({
   url : 'your_url',
   type : 'POST',
   data : formData,
   processData: false,
   contentType: false,
   success : function(data) {
       # success
   }
});

Jquery/Ajax Documentation jQuery / Ajax文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM