How to upload image to Asp.net MVC using Ajax request

How to upload an image to Asp.net MVC using an Ajax request I have one controller and its view file should use an Ajax request.

Index controller

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

and his view

+4
source share
1 answer

HTML code for the input type file, so we will call the input type from it id

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

    }
+10
source

Source: https://habr.com/ru/post/1606529/


All Articles