問(wèn)題描述
我在表單中有一個(gè) <s:file>
標(biāo)簽,它生成一個(gè) HTML <input type="file">
.當(dāng)我通過(guò)表單提交(例如提交按鈕等)提交表單時(shí),動(dòng)作方法中的一切正常.但是,當(dāng)我將代碼更改為:
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 類(lèi)中定義如下(帶有 setter 和 getter):
The file field is defined in the action class as follow (with setter and getter):
private File impFileUrl;
是不是因?yàn)楝F(xiàn)在表單被序列化了,導(dǎo)致后端不能再正確設(shè)置文件字段?
Is it because now the form is serialized so that the file field can no longer be set properly in the backend?
推薦答案
這是因?yàn)?jQuery.serialize() 只序列化輸入元素,而不是其中的數(shù)據(jù).
It is because jQuery.serialize() serializes only input elements, not the data in them.
只有成功的控件"被序列化為字符串.不提交按鈕值被序列化,因?yàn)楸韱尾皇鞘褂冒粹o.對(duì)于要包含在序列化的表單元素的值字符串,元素必須有一個(gè)名稱(chēng)屬性.復(fù)選框的值和單選按鈕(單選"或復(fù)選框"類(lèi)型的輸入)包括在內(nèi)僅當(dāng)它們被檢查時(shí).來(lái)自文件選擇元素的數(shù)據(jù)不是序列化.
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上傳文件.可能會(huì)使用其他功能或插件來(lái)發(fā)送 FormData
對(duì)象.
But it doesn't mean that you can't upload files with ajax. Additional features or plugins might be used to send FormData
object.
如果您設(shè)置了正確的選項(xiàng),您也可以將 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
});
這篇關(guān)于為什么輸入 type=file 不能與 $.ajax 一起使用?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!