send image from view to controller using ajax in MVC

In this tutorial I will show how can we transfer uploaded image from view to controller using ajax in asp.net MVC Razor.

Bellow is file upload control using which I will select file.

<input type='file' name='imageUpload' id='imageUpload' />

On file selection we will fire an event which will transfer selected file from view to controller.
Bellow is OnChange event called for upload control.

      $("#imageUpload").change(function () {
         var data = new FormData();
         var files = $("#imageUpload").get(0).files;
         if (files.length > 0) {
            data.append("helpSectionImages", files[0]);
         }
         $.ajax({
            url: '@Url.Action("PostImage","Home")',
               type: "POST",
         processData: false,
         contentType: false,
         data: data,
         success: function (response) {
             alert("uploaded");
         },
         error: function (er) {
            alert("error");
         }

      });
      });

In this on change event we will create FormData object & will add selected file & will send that object to controller using ajax.

Here I am calling PostImage action of Home controller.
Bellow is PostImage action

      [HttpPost]
      public ActionResult PostImage(HttpPostedFileBase helpSectionImages) {
         if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any()) {
            var pic = System.Web.HttpContext.Current.Request.Files["helpSectionImages"];

            Image img = Bitmap.FromStream(pic.InputStream) ;
           }
        }

Note: name of parameter “helpSectionImages” in action should be same as name of file added in FormData object in ajax call.

admin