Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...