最近用到了文件上传功能,下面给出ASP.NET MVC文件上传的一个简单示例:
一、前端代码
@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new {enctype = "multipart/form-data"})) { <div>文件上传:<input type="file" name="myFile"/></div> <input type="submit" value="提交"/> }
二、后台代码
/// <summary> /// 上传文件 /// </summary> /// <returns>上传文件结果信息</returns> [HttpPost] public ActionResult UploadFile() { HttpPostedFileBase file = Request.Files["myFile"]; if (file != null) { try { var filename = Path.Combine(Request.MapPath("~/Upload"), file.FileName); file.SaveAs(filename); return Content("上传成功"); } catch (Exception ex) { return Content(string.Format("上传文件出现异常:{0}", ex.Message)); } } else { return Content("没有文件需要上传!"); } }
时间: 2024-12-23 14:35:22