目前遇到一個需求,ajax提交數據的同時上傳文件, 發現FormData是一個很有用的屬性。在mvc中以下代碼直接將表單數據和上傳的文件提交到一個Model,確實爽的不得了。
var TestTakerUI_form = $("#TestTakerUI_form");
var url = TestTakerUI_form.attr('action');
var form = document.getElementById("TestTakerUI_form")
var fileObj = document.getElementById("LogoFile").files;
var formdata = new FormData(form);
formdata.append("LogoFile", fileObj);
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('POST', url, true);
xhr.onreadystatechange = function (response) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
$("#content_5").html(xhr.responseText);
}
}
};
xhr.send(formdata);
var form = document.getElementById("TestTakerUI_form")
var fileObj = document.getElementById("LogoFile").files;
var formdata = new FormData(form);
formdata.append("LogoFile", fileObj);
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('POST', url, true);
xhr.onreadystatechange = function (response) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
$("#content_5").html(xhr.responseText);
}
}
};
xhr.send(formdata);
服務端model,直接將文件傳了過來,並且model里面包含了其他的表單屬性
更多關於formdata的信息,請參考:https://developer.mozilla.org/en-US/docs/Web/API/FormData
但是Formdata並不是每種瀏覽器都支持,如下所示:
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 7+ | 4.0 (2.0) | 10+ | 12+ | 5+ |
append with filename | (Yes) | 22.0 (22.0) | ? | ? | ? |
因此,可以考慮其他上傳組件:
http://www.uploadify.com/,
http://jquery.malsup.com/form/,
http://www.phpletter.com/Demo/AjaxFileUpload-Demo/,
http://www.fyneworks.com/jquery/multiple-file-upload/
也可以google下uploader,發現可以用的組件還真是多啊!