0

I am trying to upload multiple images using ASP.NET MVC and Ajax. Was able to get the code to work and upload 1 image but finding it difficult to upload multiple images in a separate image folder. Appreciate any help.

please find the HTML code

  <div class="row" style="margin-top:20px;">
            <div class="col-md-6 col-sm-6 col-xs-12">
                <div class="col-md-4" style="margin:0 !important;"><label style="margin-top:5px; margin-left: -15px;">Select image</label></div>
                <div class="col-md-8" style="margin:0 !important;">
                    <span class="control-fileupload ">
                        <input type="file" id="Fimage0" name="ImageUpload" onchange='uploadImage(0)' class="form-control clearMembers">                            
                    </span>
                </div>
            </div>
            <div class="col-md-6 col-sm-6 col-xs-12">
                <div class="col-md-4" style="margin:0 !important;"><label style="margin-top:5px; margin-left: -15px;">Select image (Spouse)</label></div>
                <div class="col-md-8" style="margin:0 !important;">
                    <span class="control-fileupload ">
                        <input type="file" id="Fimage1" name="ImageUpload" onchange='uploadImage(1)' class="form-control clearMembers">
                    </span>
                </div>
            </div>
        </div>

please find the script,

as i have done that get all value in array but i unable to pass the value to ajax append please fine the below ajax.

var file; 
        var imagearray = [];
        function uploadImage(Imageid) {
            debugger
            var fileUpload = document.getElementById("Fimage" + Imageid);
            file = fileUpload.files[i];
            imagearray.push(file)    
        }

please find the ajax

function SaveFamilyInfoDatatoDB() {

            var formData = new FormData();

            formData.append("Name", $('#FName').val());
            //formData.append("file", $('#Fimage')[0].files[0]);
            //formData.append("file", $('#FimageSpouse')[0].files[0]);
            formData.append("file", $('#Fimage0')[0].files[0]);

            $.ajax({
                type: "POST",
                url: "@Url.Action("SaveAndUpdateFamilyInfo","FamilyInfo")",
                datatype: "JSON",
                processData: false,
                contentType: false,
                data: 

                    formData,
                processData: false,
                contentType: false,
                success: function (Result) {                   
                    if (Result.type == "success") {                      
                        pushToDocumentArray();                        
                    }
                    else if (Result.type == "NicValidation") {
                        alert("NIC Already Added")
                    } else {
                        alert("11")
                    }
                }
            })
        }

please find the controller

public JsonResult SaveAndUpdateFamilyInfo(Family_Information FamilyInfoMainDeatils, HttpPostedFileBase[] file)
        {
            try
            {
                string imgepath = "Null";
                if (file != null)
                {
                    for (int i = 0; i < file.Length; i++)
                    {

                    }
                    //string filename = file.FileName;
                    //imgepath = filename;
                    //string extension = Path.GetExtension(file.FileName);
                    ////  filename = filename + DateTime.Now.ToString("yymmssfff") + extension;
                    ////  person.ImagePath = "~/Ima/" + filename;
                    //var path = Path.Combine(Server.MapPath("~/Images"), FamilyInfoMainDeatils.Name + filename);
                    //file.SaveAs(path);
                }

                string FamilyInfoID = Adapter.SaveAndUpdateFamilyInfo_(FamilyInfoMainDeatils, imgepath);

                return Json(new { type = FamilyInfoID });
            }
            catch (Exception ex)
            {
                Log.ErrorLog(ex.Message);
                throw;
            }

        }
DloveJ
  • 13
  • 1
  • 1
  • 8
  • Refer [How to append whole set of model to formdata and obtain it in MVC](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681). Simply change the parameter in your POST method to `HttpPostedFileBase[] ImageUpload` (to match the name of the input), and simply use `var formdata = new FormData($('form').get(0));` (and delete your `uploadImage()` function and the `onchange` in your inputs. –  Mar 20 '18 at 06:25
  • hi Stephen i have get the error when using (var formdata = new FormData($('form').get(0))) --- formData is not defined - error. – DloveJ Mar 20 '18 at 07:07
  • Well your currently doing `var formData = new FormData();` and not getting that error, so what you claiming is not possible (but it should not be wrapped in parethesis) –  Mar 20 '18 at 07:13
  • please check the below link https://stackoverflow.com/a/49378686/9520535 – DloveJ Mar 20 '18 at 07:40
  • You need to delete that answer - its NOT and answer! And you do not need the `formData.append` lines of code - the `var formdata = new FormData($('form').get(0));` already add all the values of the form controls as explained in the link I gave you (assuming you generate your view correctly which you have not - ALWAYS ALWAYS generate you view with the `@Html.***For(m => m.yourProperty)` methods. –  Mar 20 '18 at 07:45
  • but most importantly, javascript is case sensitive - you declared a variable named `formdata` (all lower case) which is not the same a `formData` (upper case `D`) –  Mar 20 '18 at 07:47

1 Answers1

0

DloveJ

you can do one thing, take another folder with the name "Temporary". While choosing images through "File Upload" input save them to "Temporary" folder instead of direct saving to main folder & for preview purpose display it from "Temporary" folder. When click on "Upload image" button just copy all files from "Temporary" folder to your main "Destination folder" and make empty "Temporary" folder. While copying images from "Temporary" folder to "Destination Folder" you can perform different operations like change the filename, save image path to DB etc.

Edit :

Here, below is the code snippet, please go through it and let me know for any query:

Step 1: First create 2 folders. One with the name Temp and Second with [Your Destination Folder Name].

Step 2: Create user interface.

<style>
  img {
      border: 1px solid #ddd;
      border-radius: 4px;
      padding: 5px;
      width: 150px;
   }
</style>
 <div class="row" style="margin-top:20px;">
    <div class="col-md-6 col-sm-6 col-xs-12">
        <div class="col-md-4" style="margin:0 !important;">
            <label style="margin-top:5px; margin-left: -15px;">
                Select image
            </label>
        </div>
        <div class="col-md-8" style="margin:0 !important;">
            <span class="control-fileupload ">
                <input type="file" id="flImage" name="ImageUpload"
                       onchange='uploadTempImage()' class="form-control">
            </span>
        </div>
    </div>
    <div id="imgPreview"></div>
</div>
<div>
<button id="btnSaveImage" onclick="Upload()">Upload Files</button>
</div>

Step 3: Write a code to make ajax call and to save images.

  function UploadTempImage() {
    var formData = new FormData();
    formData.append('file', $('#flImage')[0].files[0]);
    $.ajax({
        type: 'post',
        url: '/TestImage/SaveToTemp',
        data: formData,
        success: function (response) {
            if (response != null) {
                var my_path = "/temp/" + response;
                var image = '<img src="' + my_path + '" alt="image" style="width:150px">';
                $("#imgPreview").append(image);
            }
        },
        processData: false,
        contentType: false,
        error: function () {
            alert("Whoops something went wrong!");
        }
    });
}

function Upload() {

    $.ajax({
        type: 'get',
        url: '/TestImage/SaveToMainFolder',
        success: function (response) {
            if (response != null) {
                alert(response);
            }
        },

    });
}

Step 4: Write a method to handle ajax request into controller.

    /// <summary>
    /// Save file to Temp folder.
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [HttpPost]
    [ValidateInput(false)]
    public JsonResult SaveToTemp(HttpPostedFileBase file)
    {
        try
        {
            string filename = "";
            string imgepath = "Null";
            if (file != null)
            {
                filename = file.FileName;
                imgepath = filename;
                string extension = Path.GetExtension(file.FileName);
                filename = DateTime.Now.Ticks + filename;
                var path = Path.Combine(Server.MapPath("~/Temp/"), filename);
                file.SaveAs(path);
            }
            return Json(filename, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    /// <summary>
    /// This method is used to move files from Temp folder to Destinatin folder.
    /// </summary>
    /// <returns></returns>
    public JsonResult SaveToMainFolder()
    {
        //This method has been copied from here:https://stackoverflow.com/a/15140431/5202777 
        string fileName = "";
        string destFile="";
        string sourcePath = Server.MapPath("~/Temp/");
        string targetPath = Server.MapPath("~/[Your Destination Folder Name]/");
        if (System.IO.Directory.Exists(sourcePath))
        {
            string[] files = System.IO.Directory.GetFiles(sourcePath);
            // Copy the files. 
            foreach (string file in files)
            {
                fileName = System.IO.Path.GetFileName(file);
                destFile = System.IO.Path.Combine(targetPath, fileName);
                System.IO.File.Copy(file, destFile, true);
            }
            RemoveFiles();
        }
        return Json("All Files saved Successfully.", JsonRequestBehavior.AllowGet);
    }

    /// <summary>
    /// Make Temp folder empty once all files are copied to destination folder.
    /// </summary>
    public void RemoveFiles() {
        string sourcePath = Server.MapPath("~/Temp/");
        string[] files = System.IO.Directory.GetFiles(sourcePath);
        foreach (string file in files)
        {
            if (System.IO.File.Exists(System.IO.Path.Combine(sourcePath, file)))
            {
                try
                {
                    System.IO.File.Delete(file);
                }
                catch (System.IO.IOException e)
                {
                    return;
                }
            }
        }
    }

Please let me know if it helped.

KRS
  • 41
  • 6
  • hi Krs, please give me some more details because as im send image and data in the ajax, formData.append("Wedding_Date", $('#FWeddingDate').val()); formData.append("Join_Date_Church", $('#FDateofjoin').val()); formData.append("Baptism_Status", $("input[name='FBaptismradio']:checked").val()); formData.append("Baptism_Date", $('#FBaptism').val()); formData.append("file", $('#Fimage')[0].files[0]); – DloveJ Mar 20 '18 at 07:02