目前遇到一个需求,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,发现可以用的组件还真是多啊!