Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a Image in Asp.net MVC using Ajax request

How to upload a Image in Asp.net MVC using Ajax request I have single controller and its view file have to use Ajax request.

Index Controller

public ActionResult Index()
{
     return View();
}

and its view

like image 917
ZCoder Avatar asked Sep 09 '15 04:09

ZCoder


People also ask

Can we upload image using Ajax?

We can send the file to the server using the JQuery Ajax method. And we also preview image file before uploading on the server.

How upload Ajax file to MVC?

Go to File->New->Project. Give a suitable name to the Application. Click OK. As you can see in the above image, two files are sent to C# ActionMethod, and both will be uploaded now.


1 Answers

Textbox with id="imageUploadForm"

<input type="file" id="imageUploadForm"  name="image" multiple="multiple" />

Ajax function

 $(document).ready(function() {
       $("#imageUploadForm").change(function() {
         var formData = new FormData();
         var totalFiles = document.getElementById("imageUploadForm").files.length;
         for (var i = 0; i < totalFiles; i++) {
           var file = document.getElementById("imageUploadForm").files[i];
           formData.append("imageUploadForm", file);
         }
         $.ajax({
           type: "POST",
           url: '/Home/Upload',
           data: formData,
           dataType: 'json',
           contentType: false,
           processData: false
             //success: function(response) {
             //    alert('succes!!');
             //},
             //error: function(error) {
             //    alert("errror");
             //}
         }).done(function() {
           alert('success');
         }.fail(function( xhr, status, errorThrown ) {
             alert('fail');
           };
         });
       });

Controller Function

      [HttpPost]
        public void Upload()
        {

if(Request.Files.Count != 0){

            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];

                var fileName = Path.GetFileName(file.FileName);

                var path = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
                file.SaveAs(path);
            }

        }

}
like image 146
ZCoder Avatar answered Oct 30 '22 22:10

ZCoder