3

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

In the backend, the file field is always null.

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?

Roman C
  • 49,761
  • 33
  • 66
  • 176
user6332430
  • 442
  • 10
  • 29

1 Answers1

3

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.

But it doesn't mean that you can't upload files with ajax. Additional features or plugins might be used to send 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
});
Roman C
  • 49,761
  • 33
  • 66
  • 176