输入类型=文件无法使用$ .ajax?

我在表单中有一个标记,它生成一个HTML 。 当我通过表单提交(例如提交按钮等)提交表单时,一切都在动作方法中正常工作。 但是,当我将我的代码更改为:

 $.ajax({ url: "actionClass!actionMethodA.action", type: "POST", error: function(XMLHttpRequest, textStatus, errorThrown) { alert('Error ' + textStatus); alert(errorThrown); alert(XMLHttpRequest.responseText); }, data: $(form).serialize(), success: function(data) { ... } }); 

在后端, file字段始终为null

文件字段在操作类中定义如下(使用setter和getter):

 private File impFileUrl; 

是因为现在表单已序列化,以便后端无法再正确设置文件字段?

这是因为jQuery.serialize()仅序列化输入元素,而不是序列化输入元素。

只有“成功控件”被序列化为字符串。 没有提交按钮值被序列化,因为表单未使用按钮提交。 要使表单元素的值包含在序列化字符串中,该元素必须具有name属性。 复选框和单选按钮(“radio”或“checkbox”类型的输入)中的值仅在选中时才包括在内。 文件选择元素中的数据未序列化。

但这并不意味着您无法使用ajax上传文件。 可以使用其他function或插件来发送FormData对象 。

如果设置了正确的选项,也可以将FormData与jQuery一起使用:

 var fd = new FormData(document.querySelector("form")); fd.append("CustomField", "This is some extra data"); $.ajax({ url: "actionClass!actionMethodA.action", type: "POST", data: fd, processData: false, // tell jQuery not to process the data contentType: false // tell jQuery not to set contentType });