Introduction:

In this article we will explain how to upload image in mvc or how to save image in mvc or how to upload image using ajax in mvc on file upload change event jquery.

Description:

Image Upload is very important functionality in web application. It is most orderly needed whereas registering profile somebody with profile image, slider images etc. I have explained during this article, how to upload image in MVC application (Razor Engine) using Ajax in jquery and preview image instantly.  

Now here, I have included main features like Upload Image, Re size Image, Give New File Name using GUID and finally preview image.

Step 1: add two html controls in your Razor page  

1.   Input File element

2.   Image element

 

For example you can see below:

<input class="col-md-8" type="file" name="userimage" id="userimage">
<img src="" class="img-circle" id="imgPreview">

 Step 2:  now write jQuery Call to MVC Controller Method 

 <script>
    $(document).ready(function () {
        $('.input-group.date').datepicker();
           
        $("#userimage").change(function () {
            var data = new FormData();
            var files = $("#userimage").get(0).files;
            if (files.length > 0) {
                data.append("MyImages",files[0]);
            }
 
            $.ajax({
                url: "/Account/UploadFile",
                type: "POST",
                processData: false,
                contentType: false,
                data: data,
                success: function (response) {
                    //code after success                   
                    $("#imgPreview").attr('src', '/Images/User/' + response);
                },
                error: function (er) {
                    alert(er);
                }
 
            });
        });
    });
</script>

Step 3:  Here is write your logic to create a new file name, re size image and upload finally to specific folder "images"

        [HttpPost]
        public JsonResult UploadFile()
        {
            string _imgname = string.Empty;
            if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
            {
                var pic = System.Web.HttpContext.Current.Request.Files["MyImages"];
                if (pic.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(pic.FileName);
                    var _ext = Path.GetExtension(pic.FileName);
 
               _imgname = WebSecurity.CurrentUserId.ToString();
              var _comPath = Server.MapPath("/Images/User/User_") + _imgname +_ext;
                    _imgname = "User_" + _imgname + _ext;
 
                    ViewBag.Msg = _comPath;
                    var path = _comPath;
 
                    // Saving Image in Original Mode
                    pic.SaveAs(path);
 
                    // resizing image
                    MemoryStream ms = new MemoryStream();
                    WebImage img = new WebImage(_comPath);
 
                    if (img.Width > 200)
                        img.Resize(200, 200);
                    img.Save(_comPath);
                    // end resize
 
                    var data = Uow.UserProfile.GetByID(WebSecurity.CurrentUserId);
                    data.ImageUrl = "/Images/User/" +_imgname;
                    Uow.UserProfile.Update(data);
                    Uow.Save();
                }
            }
            return Json(Convert.ToString(_imgname), JsonRequestBehavior.AllowGet);
        }

Output:

After completed all above steps run your application and browse a image , after selecting a image it will save and preview your image like below:

Upload Image using jquery ajax in MVC

I hope it will help to you after reading it.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like