標籤:method base ase orm stream blog function round query
需要引用js jquery.form
前端代碼
<form action="/Save" id="mainForm" method="post" enctype="multipart/form-data"> <div class="portlet-body form-horizontal form-bordered form-row-stripped"> <div class="row-fluid"> <div class="control-group"> 匯入檔案:<input type="file" name="FilePath" class="file" id="fileField"> </div> </div> </div> <div class="form-actions navbar-fixed-bottom"> <button id="submit" type="submit" class="btn blue"><i class="icon-ok"></i>提交</button> </div></form> <script src="/Content/Scripts/jquery.form.js"></script><script> $(function() { $("#mainForm").attr("enctype", "multipart/form-data"); $("#fileField").on("change", function() { $("#mainForm").attr("action", "/ImportFile"); $(‘form‘).ajaxSubmit({ success: function(data) { if (data) { //todo } else { alert("解析檔案異常,請檢查上傳檔案"); } $("#mainForm").attr("action", "/Save"); }, }); }); });</script>
後端代碼
[HttpPost]public JsonResult ImportFile(FormCollection collection){ object model = null; try { HttpPostedFileBase fostFile = Request.Files["FilePath"]; Stream streamfile = fostFile.InputStream; var reader = new StreamReader(streamfile); string text = reader.ReadToEnd(); model = XmlHelper.XmlDeserialize<Model>(text, Encoding.UTF8); } catch (Exception ex) { throw new Exception(); } return Json(model, JsonRequestBehavior.AllowGet);}
這樣上傳檔案的問題就解決了。
Ajax非同步上傳檔案