【问题标题】:Asp.net MVC Image Upload and PreviewAsp.net MVC 图像上传和预览
【发布时间】:2020-03-11 16:21:59
【问题描述】:

我有一个项目。有一个 Portfolio 页面,其中包含项目信息、项目相关类别、项目相关技术和项目相关图像。我希望将项目的图片一张一张添加,并在需要时删除。最后,当我按下保存按钮时,我希望将所有信息保存到数据库中,并将图片保存在一个文件夹中。

这是我的投资组合模型

    public Portfolio()
    {
        this.Categories = new HashSet<Category>();
        this.Technologies = new HashSet<Technology>();
        this.Images = new HashSet<Image>();
    }
    public int Id { get; set; }

    [Display(Name ="Project Name"),Required(ErrorMessage ="*")]
    public string ProjectName { get; set; }
    [Display(Name = "Date")]
    public DateTime Date { get; set; }
    [Display(Name = "Url")]
    public string URL { get; set; }
    [Display(Name = "Description")]
    public string Description { get; set; }
    public virtual ICollection<Technology> Technologies { get; set; }
    public virtual ICollection<Category> Categories { get; set; }
    public virtual ICollection<Image> Images { get; set; }

这是我的图像模型

    public Image()
    {
        this.Portfolios = new HashSet<Portfolio>();
    }
    public int Id { get; set; }
    public string URL { get; set; }
    [NotMapped]
    public HttpPostedFileBase[] files { get; set; }
    public int PortfolioId { get; set; }
    public virtual ICollection<Portfolio> Portfolios { get; set; }

这是我的创建动作

    public ActionResult Create(Portfolio portfolio, string[] Cat, string[] Tech, HttpPostedFileBase img)
    {

        //TODO:Image add
        if (ModelState.IsValid)
        {
            if (Cat != null)
            {
                portfolio.Categories = new List<Category>();
                foreach (var item in Cat)
                {
                    var categoryToAdd = context.Category.Find(int.Parse(item));
                    portfolio.Categories.Add(categoryToAdd);
                }
            }
            if (Tech != null)
            {
                portfolio.Technologies = new List<Technology>();
                foreach (var item in Tech)
                {
                    var technologyToAdd = context.Technology.Find(int.Parse(item));
                    portfolio.Technologies.Add(technologyToAdd);
                }
            }
            context.Portfolio.Add(portfolio);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View();
        }
    }

这是我的创建视图

    <div class="card-body">
    @using (Html.BeginForm("Create", "Portfolio", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        <div class="form-group">
            @Html.LabelFor(m => m.ProjectName, new { @class = "control-label" })
            @Html.ValidationMessageFor(m => m.ProjectName, "", new { @class = "text-danger" })
            @Html.EditorFor(s => s.ProjectName, new { htmlAttributes = new { @class = "form-control" } })
        </div>
        <div class="form-group">
            @Html.LabelFor(m => m.Date, new { @class = "control-label" })
            @Html.ValidationMessageFor(m => m.Date, "", new { @class = "text-danger" })
            @Html.EditorFor(s => s.Date, new { htmlAttributes = new { @class = "form-control" } })
        </div>
        <div class="form-group">
            @Html.LabelFor(m => m.URL, new { @class = "control-label" })
            @Html.ValidationMessageFor(m => m.URL, "", new { @class = "text-danger" })
            @Html.EditorFor(s => s.URL, new { htmlAttributes = new { @class = "form-control" } })
        </div>
        <div class="form-group">
            @Html.LabelFor(m => m.Description, new { @class = "control-label" })
            @Html.ValidationMessageFor(m => m.Description, "", new { @class = "text-danger" })
            @Html.EditorFor(s => s.Description, new { htmlAttributes = new { @class = "form-control" } })
        </div>
        <div class="form-group">
            @Html.LabelFor(m => m.Categories, new { @class = "control-label" })
            @* @Html.ListBoxFor(m=>m.Categories,(IEnumerable<SelectListItem>)ViewBag.Cat)*@
            @Html.ListBox("Cat", null, new { @class = "form-control" })
        </div>
        <div class="form-group">
            @Html.LabelFor(m => m.Technologies, new { @class = "control-label" })
            @* @Html.ListBoxFor(m=>m.Categories,(IEnumerable<SelectListItem>)ViewBag.Cat)*@
            @Html.ListBox("Tech", null, new { @class = "form-control" })
        </div>
        <div class="form-group">
            <script src="~/Scripts/jquery-2.1.3.min.js"></script>
            <script>
                //$(document).ready(function () {
                //    $("#fileButton").click(function () {
                //        var files = $("#fileInput").get(0).files;
                //        var fileData = new FormData();
                //        for (var i = 0; i < files.length; i++) {
                //            fileData.append("fileInput", files[i]);
                //        }
                //        $('#files').val(fileData);
                //    });
                //});
                $(document).ready(function () {
                    var i = 1;
                    function readURL(input) {
                        if (input.files && input.files[0]) {
                            var reader = new FileReader();
                            reader.onload = function (e) {
                                var img = '<div id="imageItem' + i + '" style="position:relative;width:100px;">' +
                                    '<i onclick="remove(\'imageItem' + i + '\')"' + 'style="position:absolute;right:5px;cursor:pointer;">X</i>' +
                                    ' <img src="' + e.target.result + '" width="100" /><input type="hidden" name="img" value="' + e.target.result + '" />' +
                                    '</div>';
                                $('#imageList').append(img);
                            }
                            reader.readAsDataURL(input.files[0]);
                            i = i + 1;
                        }
                    }
                    $("#fu").change(function () {
                        readURL(this);
                    });

                });
                function remove(id) {
                    $('#' + id).remove();
                }
            </script>
            <div class="form-group">
                <div class="row">
                    <div class="col-6">
                        @Html.LabelFor(m => m.Images, new { @class = "control-label" })
                        <input type="file" id="fu" class="form-control" />
                    </div>
                    <div class="col-6">
                        <div id="imageList">
                            @*<div id="imageItem1" style="position:relative;width:100px;">
                                    <i onclick="remove('imageItem1')" style="position:absolute;right:5px;cursor:pointer;">X</i>
                                    <img src="~/images/portfolio/1.jpg" width="100" />
                                </div>*@
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="form-group row">
            <div class="col-6">
                <button class="btn btn-outline-success">Save</button>
            </div>
            <div class="col-6 text-right">
                <a href="@Url.Action("Index","Portfolio")" class="text-primary text-decoration-none"><i class="fa fa-arrow-left text-primary"></i> Back To List</a>
            </div>
        </div>
    }
</div>

和图片一样,我想先选择图片,然后点击保存按钮保存信息。 enter image description here

【问题讨论】:

  • 问候@mert,我已经添加了在 .NET MVC 应用程序中保存图像或媒体文件的流程,如果您需要更多详细信息,请告诉我会相应地更新帖子。

标签: asp.net-mvc image-uploading image-preprocessing


【解决方案1】:

查看


脚本和 CSS

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
    .preview-images-zone {
        width: 100%;
        border: 1px solid #ddd;
        min-height: 90px;
        /* display: flex; */
        padding: 5px 5px 0px 5px;
        position: relative;
        overflow: auto;
    }

        .preview-images-zone > .preview-image:first-child {
            height: 90px;
            width: 90px;
            position: relative;
            margin-right: 5px;
        }

        .preview-images-zone > .preview-image {
            height: 90px;
            width: 90px;
            position: relative;
            margin-right: 5px;
            float: left;
            margin-bottom: 5px;
        }

            .preview-images-zone > .preview-image > .image-zone {
                width: 100%;
                height: 100%;
            }

                .preview-images-zone > .preview-image > .image-zone > img {
                    width: 100%;
                    height: 100%;
                }

            .preview-images-zone > .preview-image > .tools-edit-image {
                position: absolute;
                z-index: 100;
                color: #fff;
                bottom: 0;
                width: 100%;
                text-align: center;
                margin-bottom: 10px;
                display: none;
            }

            .preview-images-zone > .preview-image > .image-cancel {
                font-size: 18px;
                position: absolute;
                top: 0;
                right: 0;
                font-weight: bold;
                margin-right: 10px;
                cursor: pointer;
                display: none;
                z-index: 100;
            }

    .preview-image:hover > .image-zone {
        cursor: move;
        opacity: .5;
    }

    .preview-image:hover > .tools-edit-image,
    .preview-image:hover > .image-cancel {
        display: block;
    }

    .ui-sortable-helper {
        width: 90px !important;
        height: 90px !important;
    }

    .container {
        padding-top: 50px;
    }
</style>
 <script>
        $(document).ready(function () {
            $(document).on('change', '.btn-file :file', function () {
                var input = $(this),
                    label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
                input.trigger('fileselect', [label]);
            });

            $('.btn-file :file').on('fileselect', function (event, label) {

                var input = $(this).parents('.input-group').find(':text'),
                    log = label;

                if (input.length) {
                    input.val(log);
                } else {
                    if (log) alert(log);
                }

            });
            function readURL(input) {
                if (input.files && input.files[0]) {
                    var reader = new FileReader();

                    reader.onload = function (e) {
                        $('#img-upload').attr('src', e.target.result);
                    }

                    reader.readAsDataURL(input.files[0]);
                }
            }

            $("#imgInp").change(function () {
                readURL(this);
            });
        });

    </script>

图片上传控制器

 @Html.TextBoxFor(model => model.YOUR_MODEL_DATA, new { Type = "file", @class = "form-input-styled", id = "imgInp" })

图片预览

<img id='img-upload' class="img-fluid" alt=" " width="200" height="200" />

控制器


[HttpPost]
public ActionResult Create(YOUR_TABLE tbl)
{
   tbl.Images  = tbl.files.FileName;
   tbl.files.SaveAs(YOUR_PATH);
}

【讨论】:

  • 这迫使您上传图片,因为 GPDR 不允许在 2020 年将此评论留给其他人。
【解决方案2】:

@mert 在 .NET MVC 中使用 HttpPostedFileBase 上传图片时需要注意 2-3 件事。

1) 表格必须是enctype = "multipart/form-data"

2) 输入类型文件的名称应与类对象的名称完全相同。

前任

//In .cshtml file  
<input type='file' name="file"/>

//In Controller file
[HttpPost]
public ActionResult Index(HttpPostedFileBase file){
   // You controller code
   return View();
}

3)HttpPostedFileBase 控制器端获取文件后,您需要验证对象是否为空,以及要保存文件的文件夹路径是否存在。

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
    if (file != null)
    {
        var directoryPath = Server.MapPath("~/FolderName");
        if (!Directory.Exists(directoryPath))
        {
            Directory.CreateDirectory(directoryPath);
        }

        var fileGuid = Guid.NewGuid();
        var filename = string.Concat(fileGuid, Path.GetExtension(file.FileName));
        var savePath = Path.Combine(directoryPath, filename);
        file.SaveAs(savePath);
    }

    return View();
}

【讨论】:

  • 这不是回答他的两个观点,只是保存而不是预览
  • 感谢@rogue39nin 指出,是的,忘记添加预览代码了。但是为了预览它有一个简单的 jQuery 代码。您可以从研究中获得或将使用该代码再次更新此帖子。
猜你喜欢
  • 2014-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多