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

2022-01-16 00:00:00 file-upload jquery javascript ajax struts2

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

I have a <s:file> tag inside the form which generates a HTML <input type="file">. When I submit the form via form submission (e.g. submit button, etc.) everything works fine in the action method. However, when I change my code to:

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

file 字段在 action 类中定义如下(带有 setter 和 getter):

The file field is defined in the action class as follow (with setter and getter):

private File impFileUrl;

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

Is it because now the form is serialized so that the file field can no longer be set properly in the backend?

推荐答案

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

It is because jQuery.serialize() serializes only input elements, not the data in them.

只有成功的控件"被序列化为字符串.不提交按钮值被序列化,因为表单不是使用按钮.对于要包含在序列化的表单元素的值字符串,元素必须有一个名称属性.复选框的值和单选按钮(单选"或复选框"类型的输入)包括在内仅当它们被检查时.来自文件选择元素的数据不是序列化.

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 对象.

But it doesn't mean that you can't upload files with ajax. Additional features or plugins might be used to send FormData object.

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

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

相关文章