Upload Image MVC .net Form Using and Show Image
https://www.c-sharpcorner.com/blogs/how-to-upload-image-and-save-image-in-project-folder-in-mvc1
=====
index.php
==
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<img id="user_img" height="100" width="90" style="border:solid" />
</div>
<div>
<input type="file" title="search image" id="file" name="file" onchange="show(this)" />
</div>
<div>
UserId
</div> <div> <input type="text" id="txt_id" name="id" /> </div>
<div>
UserName
</div> <div> <input type="text" id="txt_name" name="Name" /> </div>
<div>
<input type="submit" title="save" />
</div>
}
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function show(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function (e) {
$('#user_img').attr('src', e.target.result);
}
filerdr.readAsDataURL(input.files[0]);
}
}
</script>
=======
HomeController
======
[HttpPost]
public ActionResult Index(System.Web.Mvc.FormCollection fc, HttpPostedFileBase file)
{
dataUploadImageObjEntities obj = new dataUploadImageObjEntities();
tbl_detail tbl = new tbl_detail();
var allowedExtensions = new[] {
".Jpg", ".png", ".jpg", "jpeg"
};
tbl.Id= Int32.Parse(fc["Id"]);
tbl.Image_url = file.ToString(); //getting complete url
tbl.Name = fc["Name"].ToString();
var fileName = Path.GetFileName(file.FileName); //getting only file name(ex-ganesh.jpg)
var ext = Path.GetExtension(file.FileName); //getting the extension(ex-.jpg)
if (allowedExtensions.Contains(ext)) //check what type of extension
{
string name = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension
string myfile = name + "_" + tbl.Id + ext; //appending the name with id
// store the file inside ~/project folder(Img)
var path = Path.Combine(Server.MapPath("~/Img"), myfile);
tbl.Image_url = path;
//obj.tbl_detail.Add(tbl);
obj.SaveChanges();
file.SaveAs(path);
}
else
{
ViewBag.message = "Please choose only Image file";
}
return View();
}
Tidak ada komentar