刚接触MVC时间不久,所以为了练练手,决定用MVC做一个小站来熟悉熟悉,在做的过程中遇到了需要上传图片的问题,所以也就有了这篇文章。高手请绕行。
代码很简单,可以一次上传多张图片。话不多说,直接上代码。
前台代码【view】:
@using (Html.BeginForm("UpImage", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { <div id="div_upimg"> <input name="upimg" type="file" /><input type="button" value=" 增加 " onclick="add()" /><br /> </div> <input type="submit" value=" 提 交 " /> }
<script type="text/javascript">
add = function () {
var _file = $("#div_upimg [type=file]");
$("#div_upimg").append("<input type=\"file\" id=\"upimg" + _file.length + "\" name=\"upimg" + _file.length + "\" /><br />");
}
</script>
后台代码【Controller】:
[HttpPost] public ActionResult UpImage() { DateTime timeNow = DateTime.Now; string year = timeNow.Year.ToString(); string month = timeNow.Month.ToString(); string day = timeNow.Day.ToString(); string uploadPath = Server.MapPath(year + "\\" + month + "\\" + day); if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } HttpFileCollectionBase files = Request.Files; for (int i = 0; i < files.Count; i++) { if (files[i] != null) files[i].SaveAs(uploadPath + "\\" + files[i].FileName); } return Content("<script>alert('OK')</script>"); }
OK,就这点代码,很简单吧。