1.HTML
@using (Html.BeginForm("UploadFile", "Student", FormMethod.Post, new { enctype = "multipart/form-data" })) { <div style="margin:13px;padding:13px;"> <label style="float:left;">导入文件:</label> <input type="file" style="float:left;" name="myFile" /> </div> <input type="submit" value="提交" /> }
或
<form name="myfrom" id="myform" method="post" action="~/Student/UploadFile"> <div style="margin:13px;padding:13px;"> <label style="float:left;">导入文件:</label> <input type="file" style="float:left;" name="myFile" /> </div> <input type="submit" value="提交" /> </form>
2.Script:手动submit
<script> var message = "@TempData["message"]"; window.onload = function () { if (message != null && message != '' && message != "") { alert(message); } } // 手动触发表单submit var onSubmit = function () { document.getElementById("myform").submit(); } </script>
3.UploadFileAction:Import是导入视图
/// <summary> /// 页面添加一个“导入数据”读取将“文件导入.xlsx”里面的学生信息,保存至“学生.xml”文件中 /// </summary> /// <returns>上传文件结果信息</returns> [HttpPost] public ActionResult UploadFile() { HttpPostedFileBase file = Request.Files["myFile"]; if (file != null) { try { // file.FileName//文件名 // file.InputStream//文件流 TempData["message"] = "导入成功!"; return View("Import"); } catch (Exception ex) { //return Content(string.Format("上传文件出现异常:{0}", ex.Message)); TempData["message"] = string.Format("上传文件出现异常:{0}", ex.Message); return View("Import"); } } else { return View("Import"); } }