如何使用 ajax 在 asp.net mvc 中上传多张图片

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

我正在尝试使用 ASP.NET MVC 和 Ajax 上传多张图片。 能够使代码正常工作并上传 1 张图片,但发现很难在单独的图片文件夹中上传多张图片。 感谢任何帮助。

请找到 HTML 代码

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

请找到脚本,

正如我所做的那样,获取数组中的所有值,但我无法将值传递给 ajax 追加请在下面添加 ajax.

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

请找到 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")
                    }
                }
            })
        }

请找到控制器

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

你可以做一件事,取另一个名为“Temporary”的文件夹。通过“File Upload”输入选择图像时,将它们保存到“Temporary”文件夹,而不是直接保存到主文件夹并用于预览显示“临时”文件夹。单击“上传图片”按钮时,只需将所有文件从“Temporary”文件夹复制到主“目标文件夹" 并清空 "Temporary" 文件夹。将图像从“Temporary”文件夹复制到“Destination Folder”时,您可以执行不同的操作,例如更改文件名、将图像路径保存到 DB 等。

编辑:

这里是代码片段,请仔细阅读,如有任何疑问请告诉我:

第一步:首先创建2个文件夹。一个名称为 Temp,第二个名称为 [您的目标文件夹名称].

步骤 2: 创建用户界面。

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

第 3 步: 编写代码进行 ajax 调用和保存图像。

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

    });
}

第 4 步: 编写一个方法来处理 ajax 请求到控制器中。

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

如果有帮助,请告诉我。