1. cshtml 页面 form
<form id="form" method="post" action="/SaveValueBatch"
enctype="multipart/form-data">
<input type="file" name="uploadExcel" style="width:200px;" />
</form>
2. controller
- [HttpPost]
- public ActionResult SaveValueBatch(IFormCollection form)
- {
- try
- {
- var files =Request.Form.Files.Where(x => x.Name.Equals("uploadExcel"));
- // 非空限制
- if (files == null || files.Count() <= 0) { return Json(new { isSuccess = false, message = "请选择要上传的 Excel 文件" }, "text/html"); }
- // 格式限制
- var allowType = new string[] { "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};
- if (files.Any(b => !allowType.Contains(b.ContentType)))
- {
- return Json(new { isSuccess = false, message = "只能上传 Excel 2007 格式文件" }, "text/html");
- }
- // 大小限制
- if (files.Sum(b => b.Length)>= 1024 * 1024 * 4)
- {
- return Json(new { isSuccess = false, message = "上传文件的总大小只能在 4M 以下" }, "text/html");
- }
- // 写入服务器磁盘
- foreach (var file in files)
- {
- var fileName = file.FileName;
- var path = Path.Combine(_host.ContentRootPath+ "/Upload", fileName);
- using (var stream = System.IO.File.Create(path))
- {
- file.CopyTo(stream);
- }
- }
- return Json(new { isSuccess = true, message = "保存成功" }, "text/html");
- }
- catch (Exception e)
- {
- return Json(new { isSuccess = false, message = "保存失败:" + e.InnerException.Message }, "text/html");
- }
- }
- private IHostingEnvironment _host;
- public ExcelController(IHostingEnvironment host)
- {
- _host = host;
- }
来源: http://www.bubuko.com/infodetail-2651456.html