Thursday 20 July 2017

Image Upload in mvc

@model MvcApplication1.Models.ABCmodel
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
    <fieldset>
        <legend>Image</legend>
        <input type="file" name="FileUpload" id="imgInp" onchange="loadFile(event)" />
        <img id="output"  height="150" width="150" />
        <input type="submit" name="Submit" id="Submit" value="Upload" formaction="/Demo/Upload" formenctype="multipart/form-data" />     
    </fieldset>
   
}
<script>   
    function loadFile(event) {
        debugger;
            var output = document.getElementById('output');
            output.src = URL.createObjectURL(event.target.files[0]);
    }
</script>




public ActionResult Index()
        {          
            return View();
        }
[HttpPost]
        public ActionResult Upload()
        {
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];

                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
                    string relativePath = "~/Images/" + fileName;
                    file.SaveAs(path);
                                   }
            }
            return View("Index");
        }



No comments:

Post a Comment