Ajax使用包含数据和文件的FormData提交表单

时间:2018-08-09 16:10:02

标签: jquery asp.net-ajax multipartform-data

我正在尝试提交包含数据和文件的表单

$('form').submit(function(event) {
  var formData = $('form').serializeArray();
  formData.push({
    name: "logo",
    value: $("#wizard-picture")[0].files[0]
  });
  formData.push({
    name: "prologo",
    value: $("#wizard-picturep")[0].files[0]
  });
  for (var i = 0; i < list.length; i++) {
    formData.push({
      name: "Keys",
      value: list[i]
    });
  }
  console.log(formData);
  $.ajax({
    url: '/Company/Steps/',
    method: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    success: function(data) {
      debugger;
      alert("succses");
    },
    error: function(xhr, ajaxOptions, thrownError) {
      debugger;
      console.log(xhr);
      console.log(ajaxOptions);
      console.log(thrownError);

      alert(xhr.status);
      alert(thrownError);
    }
  });
});

formData正确显示在控制台中的所有数据。但在我的控制器上,它为空!!

enter image description here

1 个答案:

答案 0 :(得分:0)

要在请求中发送文件数据,您需要使用FormData对象,而不是序列化数组。

这样,您可以向form的构造函数提供对FormData元素的引用,如下所示:

$('form').submit(function(e) {
  e.preventDefault();
  var formData = new FormData($('form').get());

  $.ajax({
    url: '/Company/Steps/',
    method: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    success: function(data) {
      debugger;
      alert("succses");
    },
    error: function(xhr, ajaxOptions, thrownError) {
      debugger;
      console.log(xhr);
      console.log(ajaxOptions);
      console.log(thrownError);
    }
  });
});