1. 程式人生 > >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>");
        }