$("form").serialize()和 new FormData($('#uploadForm')[0])都是序列化表單,實現表單的異步提交,但是二者有區別
首先,前者,只能序列化表單中的數據 ,比如文本框等input select等的數據,但是對於文件,比如文件上傳,無法實現,那么這時候,FormData就上場了,
new FormData使用需要有一個注意點,
注意點一:,對於jquery的要求是,好像是 版本1.8及其以上方可支持。
另外該對象不僅僅可以序列化文件,一樣可以用作表單數據的序列化,(就是說包含了serialize()的功能);
注意點二:看腳本
$.ajax({ type: 'POST', data: uploadFormData, url: '/Artical/Publist',//TypeError: 'append' called on an object that does not implement interface FormData. processData: false, contentType: false, async: false, success: function (data) { if (typeof (data) == undefined) { alert("用戶信息已丟失,請重新登錄!"); window.parent().location.href = "/Account/Login"; } if (data.ErrorMsg == "") { alert('美文發布成功!'); } else { alert(data.ErrorMsg); } } });
注意紅色部分腳本以及說明,
processData: false, contentType: false,缺少這二者的設置,將會出現 紅色部分的錯誤提示,提交失敗。
以下是一個完整的前后台的參考腳本:
//提交文件 function submitFile() { $('.btn-publish').click(function () { //var title = $('.txt-video-title').val(); var uploadFormData = new FormData($('#uploadForm')[0]);//序列化表單,$("form").serialize()只能序列化數據,不能序列化文件 $.ajax({ type: 'POST', data: uploadFormData, url: '/Artical/Publist',//TypeError: 'append' called on an object that does not implement interface FormData. processData: false, contentType: false, async: false, success: function (data) { if (typeof (data) == undefined) { alert("用戶信息已丟失,請重新登錄!"); window.parent().location.href = "/Account/Login"; } if (data.ErrorMsg == "") { alert('美文發布成功!'); } else { alert(data.ErrorMsg); } } }); }); }
/// <summary> /// 上傳新圖片,(包含文件上傳) /// </summary> /// <returns></returns> public JsonResult UpLoad() { if (null != Session[Consts.SYSTEMUERSESSION]) { string pictureName = Request["videoTitle"];//圖片標題 string pictureInfoUrl = "";//圖片上傳之后的虛擬路徑 string pictureCategoryKey = Request["PictureCategoryList"];//視頻分類外鍵ID FileUpLoadResult fileUpLoadPicture = null;//用於輸出結果 string fileSavePath = Consts.PICTURESAVEPATH + DateTime.Now.ToString("yyyyMMdd") + "/";//當天時間最為文件夾 string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");//生成的文件名稱 //上傳,如果是視屏文件,自動生成 接切圖 fileUpLoadPicture = Request.UpLoad(fileSavePath, null, "", fileName, ""); #region 裝箱、入庫 if (fileUpLoadPicture.FileSavePath != null) { foreach (var path in fileUpLoadPicture.FileSavePath) { pictureInfoUrl += (path + ","); } pictureInfoUrl = pictureInfoUrl.Remove(pictureInfoUrl.Length - 1, 0); ColumnPicture picture = new ColumnPicture() { Id = CombHelper.NewComb(), PictureTitle = pictureName, PictureTitleDescription = pictureInfoUrl, GoodClickTimes = 888, BadClickTimes = 10, AddDate = DateTime.Now, FavoriteTimes = 888, IsEnabled = true, ToTop = 0, CustomerKey = ((Customer)Session[Consts.SYSTEMUERSESSION]).Id, ColumnsCategoryKey = new Guid(pictureCategoryKey) }; if (_pictureService.Insert(picture)) { fileUpLoadPicture = new FileUpLoadResult() { Status = true, FileSavePath = null, ErrorMsg = "" }; } } #endregion return Json(fileUpLoadPicture, JsonRequestBehavior.AllowGet); } return null; }