为什么 input type=file 不能与 $.ajax 一起使用?

Why input type=file not working with $.ajax?

我在表单中有一个 <s:file> 标签,它生成 HTML <input type="file">。当我通过表单提交(例如提交按钮等)提交表单时,在操作方法中一切正常。但是,当我将代码更改为:

$.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

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

private File impFileUrl;

是不是因为现在表单被序列化了,导致后台不能再正确设置file字段了?

这是因为jQuery.serialize()只序列化输入元素,而不是其中的数据。

Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.

但不代表不能用ajax上传文件。可能会使用其他功能或插件来发送 FormData object.

You can also use FormData with jQuery if you set the right options:

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
});