【问题标题】:Why input type=file not working with $.ajax?为什么输入 type=file 不能与 $.ajax 一起使用?
【发布时间】:2017-10-08 07:26:59
【问题描述】:

我在表单中有一个<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

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

private File impFileUrl;

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

【问题讨论】:

    标签: javascript jquery ajax file-upload struts2


    【解决方案1】:

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

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

    但这并不意味着你不能用ajax上传文件。可能会使用其他功能或插件发送FormData object

    如果你设置了正确的选项,你也可以在 jQuery 中使用FormData

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

    【讨论】:

      猜你喜欢
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-30
      • 2021-08-18
      • 2018-03-09
      相关资源
      最近更新 更多