如何使用ajax在asp.net mvc中上传多个图像 [英] how to upload multiple image in asp.net mvc using ajax

查看:122
本文介绍了如何使用ajax在asp.net mvc中上传多个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

请找到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进行罚款.

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

请找到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

您可以做一件事,将另一个文件夹命名为"临时".通过"文件上传"输入选择图片时,请将其保存到"临时"文件夹,而不是直接保存到主文件夹&出于预览目的,从"临时"文件夹中显示该文件.单击"上传图像"按钮时,只需将所有文件从"临时"文件夹复制到主"目标文件夹",然后将空白"临时"文件夹.将图像从"临时"文件夹复制到"目标文件夹"时,您可以执行不同的操作,例如更改文件名,将图像路径保存到数据库等.

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.

在这里,下面是代码段,请仔细阅读该代码段,并让我知道任何查询:

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

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

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

步骤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调用并保存图像.

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

    });
}

第4步:编写一种方法来处理Ajax请求到控制器中.

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.

这篇关于如何使用ajax在asp.net mvc中上传多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆