如何使用ajax在asp.net mvc中上传多个图像

时间:2018-03-20 05:24:57

标签: javascript jquery asp.net asp.net-mvc asp.net-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;
            }

        }

1 个答案:

答案 0 :(得分:0)

DloveJ

你可以做一件事,拿另一个名为&#34; 临时&#34;的文件夹。通过&#34; 文件上传&#34;选择图片时输入将它们保存到&#34; 临时&#34;文件夹而不是直接保存到主文件夹&amp;用于预览目的,显示来自&#34; 临时&#34;夹。点击&#34; 上传图片&#34;按钮只复制来自&#34; 临时&#34;的所有文件文件夹到您的主要&#34; 目标文件夹&#34;并使空白&#34; 临时&#34;夹。从&#34; 临时&#34;复制图像时文件夹到&#34; 目标文件夹&#34;您可以执行不同的操作,如更改文件名,将图像路径保存到DB等。

修改:

此处,以下是代码段,请仔细阅读并告知我任何疑问:

第1步:首先创建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: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;
                }
            }
        }
    }

如果有帮助,请告诉我。