Asp. net MVC Загрузка и просмотр изображений - PullRequest
0 голосов
/ 11 марта 2020

У меня есть проект. Существует страница Портфолио, которая содержит информацию о проекте, категории, связанные с проектом, технологии, связанные с проектом, и изображения, связанные с проектом. Я хочу, чтобы фотографии проекта добавлялись одна за другой и удалялись по желанию. Наконец, когда я нажимаю кнопку Сохранить, я хочу, чтобы вся информация была сохранена в базе данных, а изображения были сохранены в папке.

Это моя модель портфолио

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

Это мое представление создания

image

Как на картинке, я хочу сначала выберите изображения, а затем нажмите кнопку сохранения, чтобы сохранить информацию. введите описание изображения здесь

Ответы [ 2 ]

0 голосов
/ 14 марта 2020

@ mert: при загрузке изображения с помощью HttpPostedFileBase in. NET MVC.

1) необходимо заполнить форму. be 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, вам нужно убедиться, что объект не равен not, а путь к папке, в которой вы хотите сохранить файл, существует или нет.

[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();
}
0 голосов
/ 14 марта 2020

Просмотр


скрипт и 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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...