how to upload multiple image in asp.net mvc using ajax

北城以北 提交于 2019-12-24 22:15:59

问题


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

        }

回答1:


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.



来源:https://stackoverflow.com/questions/49376867/how-to-upload-multiple-image-in-asp-net-mvc-using-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!