【问题标题】:Passing image from modal to controller将图像从模态传递到控制器
【发布时间】:2021-06-23 11:20:06
【问题描述】:

我有以下应用程序,我必须将图像直接从模态上传到页面。

请注意:

  1. 图片已由管理员上传至此模式。
  2. 图像保存在“wwwroot”文件夹中的“静态”文件中。因此,此步骤不需要数据库。

我所需要的只是当我在模式中单击图像时,它应该被上传到视图中。因此,我可以稍后将其保存在数据库中。

这是图像库控制器

    public IActionResult Index()
    {
        var webRoot = _hostingEnvironment.WebRootPath;
        var appData = System.IO.Path.Combine(webRoot, "static");
        var files = Directory.GetFiles(appData, "*.*", SearchOption.AllDirectories);
        var model = new ImageBankViewModel()
        {
            ImagesListUrls = files.Select(i=>Path.GetFileName(i))
        };

        return View(model);
    }

    [HttpPost]
    public IActionResult Upload(ImageBankViewModel model)
    {
        if (ModelState.IsValid)
        {
            if (model.Image != null)
            {
                
                string webRootPath = _hostingEnvironment.WebRootPath;
                var path = Path.Combine(webRootPath, "static");
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);

                var extension = Path.GetExtension(model.Image.FileName);
                var newFileName = model.Type + "-" + DateTime.Now.Ticks;
                using (var filesStream = new FileStream(Path.Combine(path, newFileName + extension), FileMode.Create))
                {
                    model.Image.CopyTo(filesStream);
                }
                return RedirectToAction("Index");
            }
        }
        ImageBankViewModel modelVM = new ImageBankViewModel()
        {
            Image = model.Image,
            ImagesListUrls = model.ImagesListUrls,
            Type = model.Type
        };

        return RedirectToAction("Index",modelVM);//Unsuccessful Upload , fix invalid model
    }

    public IActionResult CreateStory()
    {
        return View();
    }

    public ActionResult GetImagesPartial()
    {
        var webRoot = _hostingEnvironment.WebRootPath;
        var appData = System.IO.Path.Combine(webRoot, "static");
        var files = Directory.GetFiles(appData, "*.*", SearchOption.AllDirectories);
        var model = new ImageBankViewModel()
        {
            ImagesListUrls = files.Select(i => Path.GetFileName(i))
        };
        return PartialView("_ImagesBankModal",model);
    }

    public void ImageDelete(string image)
    {

    }
    
      public void SelectImage(string image)
        {
           // Here I want to get the selected image from the modal
        }
    }
}

创建故事视图

@{
    ViewData["Title"] = "CreateStory";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>CreateStory</h1>
<div class="row">
    <div class="col-md-1">
        <label>Pic1</label>
    </div>
    <div class="col-md-8">
        <input type="file" accept="image/*" class="form-control" />
    </div>
    <div class="col-md-3">
        <a class="btn btn-outline-dark" asp-area="" asp-controller="Bank" asp-action="GetImagesPartial" data-toggle="modal" data-target="#myModal" id="sel">Select from image bank</a>
        <div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div id="partial"></div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-md-1">
        <label>Pic2</label>
    </div>
    <div class="col-md-8">
        <input type="file" accept="image/*" class="form-control" />
    </div>
    <div class="col-md-3">
        <button class="btn btn-outline-dark">Select from image bank</button>
    </div>
</div>

@section Scripts{
    <script type="text/javascript">
        $(function () {
            $('#sel').click(function () {
                var route = '@Url.Action("GetImagesPartial", "Bank")';
                $('#partial').load(route);
            });

        });
    </script>

}

模态局部视图

@model TestApplication.Models.ViewModels.ImageBankViewModel

<div class="modal-header">
    <h2 class="modal-title">Choose</h2>
</div>
<div class="modal-body">
    @if (Model.ImagesListUrls.Any())
    {
        <table>
            @foreach (var image in Model.ImagesListUrls)
            {
                <tr>
                    <td>
                        <a asp-area="" asp-controller="Bank" asp-action="SelectImage" asp-route-image="@image" class="btn btn-light position-absolute" style="right:0">Select</a>
                        <img src="~/static/@image" class="img-thumbnail" />
                    </td>
                </tr>
            }
        </table>
    }
    else
    {
        <h5>no images exists...</h5>
    }
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-success" data-dismiss="modal">Cancel</button>
</div>

【问题讨论】:

  • 所以..问题是什么,什么不适合你?

标签: c# asp.net asp.net-mvc asp.net-core bootstrap-modal


【解决方案1】:

您可以将所选图片的相对路径存储在输入中并将它们传递给动作。

以下是一个例子,大家可以参考一下。

索引

<form asp-action="Upload" asp-controller="ImageBank"  method="post" enctype="multipart/form-data">
<div class="row">
    <div class="col-md-1">
        <label>Pic1</label>
    </div>
    <div class="col-md-8">
        <input type="file" accept="image/*" class="form-control" name="model.Image"/>
        <ul class="selectedpic">
            
        </ul>
    </div>
    <div class="col-md-3">
        <a class="btn btn-outline-dark sel">Select from image bank</a>
    </div>
    <div class="col-md-8 addedimg">
    </div>
</div>
    <div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div id="partial"></div>
                </div>
            </div>
        </div>
    <button type="submit">submit</button>
</form>
@section Scripts{
    <script type="text/javascript">

    var currentsel="";
            $('body').on("click",".sel",function () {
                localStorage.setItem("currentsel",$(this).attr("class"));
                var route = '@Url.Action("GetImagesPartial", "ImageBank")';
                $("#myModal").modal("show");
                $('#partial').load(route);
            });            
            $('body').on("click",".selectbtn",function () {
                var currenttd=$(this).closest("td");
                console.log(currenttd.find("img").attr("src"))
                var classarry=localStorage.getItem("currentsel").split(" ");
                var currentsel="."+classarry[classarry.length-1];
                var currentaddedimg=$(currentsel).closest(".row").find(".addedimg");
                var addsrc=currenttd.find("img").attr("src");
                if(checkisexsist(currentaddedimg,addsrc)){
                    $(currentsel).closest(".row").find(".selectedpic").append("<li>"+addsrc+"</li>");
                    $(currentsel).closest(".row").find(".addedimg").append("<input hidden name='selimages' value='"+addsrc+"'/>");
                    $("#myModal").modal("hide");
                    $('#myModal').on('hidden.bs.modal', function (e) {
                      localStorage.removeItem("currentsel");
                    });
                }else{
                    alert("has selected");
                }
                
            });
            function  checkisexsist(currentaddedimg,addsrc){
                var flag=true;
                $.each(currentaddedimg.find("input[name='selimages']"), function( index, value ) {
                 if($(value).val()==addsrc){
                      flag=false;
                 }
                });
                return flag;
            }
    </script>
}

控制器

[HttpPost]
public IActionResult Upload(ImageBankViewModel model,List<string> selimages)
{
    if (ModelState.IsValid)
    {
        if (model.Image != null)
        {
            string webRootPath = _hostingEnvironment.WebRootPath;
            var path =Path.Combine(webRootPath, "static");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            var extension = Path.GetExtension(model.Image.FileName);
            var newFileName = model.Type + "-" + DateTime.Now.Ticks;
            using (var filesStream = new FileStream(Path.Combine(path, newFileName + extension), FileMode.Create))
            {
                model.Image.CopyTo(filesStream);
            }
        }
        if(selimages!=null& selimages.Count != 0)
        {
            string webRootPath = _hostingEnvironment.WebRootPath;
            var path = Path.Combine(webRootPath, "static");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            selimages.ForEach(m =>
            {
                var newFileName = Guid.NewGuid().ToString();
                var extension = "." + m.Split(".")[m.Split(".").Length - 1];
                var oldpath =webRootPath+m.Replace("/", "\\");                      var newpath = Path.Combine(path, newFileName + extension);
                System.IO.File.Copy(oldpath,newpath);
            });
        }
        return RedirectToAction("Index");
    }
    ImageBankViewModel modelVM = new ImageBankViewModel()
    {
        Image = model.Image,
        ImagesListUrls = model.ImagesListUrls,
        Type = model.Type
    };

    return RedirectToAction("Index", modelVM);//Unsuccessful Upload , fix invalid model
}

_ImagesBankModal(只给出修改的地方)

<a class="btn btn-light position-absolute selectbtn">Select</a>

结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    相关资源
    最近更新 更多