我正在尝试提交包含数据和文件的表单
$('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正确显示在控制台中的所有数据。但在我的控制器上,它为空!!
答案 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);
}
});
});