12

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

1 Answer 1

20

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);
            }

        }

}
Sign up to request clarification or add additional context in comments.

1 Comment

If Request.Files.Count is showing " 'HttpRequest' does not contain a definition for 'Files' and no accessible extension method 'Files' accepting a first argument of type 'HttpRequest' could be found (are you missing a using directive or an assembly reference?) " , then try with Request.Form.Files.Count .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.