2

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

Модель работников:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace EmployeeBase.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Byte[] Foto { get; set; }
        public DateTime BirthDate { get; set; }

        public int? DepartmentId { get; set; }
        public Department Department { get; set; }

        // If i use this - my code dosen't work
        //public HttpPostedFileBase FotoFromView { get; set; }
    }
}

Контроллер:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using System.IO;

using EmployeeBase.Models;

namespace EmployeeBase.Controllers
{
    public class HomeController : Controller
    {
        CompanyContext db = new CompanyContext();

        public ActionResult Index()
        {
            var employees = db.Employees.Include(e => e.Department);
            return View(employees.ToList());
        }

        [HttpGet]
        public ActionResult CreateEmployee()
        {
            SelectList EmpList = new SelectList(db.Departments, "Id", "Name");
            ViewBag.EmpList = EmpList;
            return View();
        }
        [HttpPost]
        public ActionResult CreateEmployee(Employee employee, HttpPostedFileBase file)
        {
            MemoryStream target = new MemoryStream();

            file.InputStream.CopyTo(target);
            byte[] data = target.ToArray();

            employee.Foto = data;
            db.Employees.Add(employee);
            db.SaveChanges();

            return RedirectToAction("Index");
        }
    }
}

Представление Index:

@model IEnumerable<EmployeeBase.Models.Employee> 

@{
    ViewBag.Title = "Company";
}

<h2>ООО "Моя Компания"</h2>
<p>
    <a href="/Home/CreateEmployee">
        <input type="button" value="New" />
    </a>
</p>
<table border="1">
    <tr>
        <th>Name</th>
        <th>Birth</th>
        <th>Foto</th>
        <th>Department</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@Html.DisplayFor(modelItem => item.Name)</td>
            <td>@Html.DisplayFor(modelItem => item.BirthDate)</td>
            <td>@Html.DisplayFor(modelItem => item.Foto)</td>
            <td>@Html.DisplayFor(modelItem => item.Department.Name)</td>
            <td>
                <a href="/Home/EditEmployee/@item.Id">
                    <input type="button" value="Edit" />
                </a>
            </td>
            <td>
                <a href="/Home/DeleteEmployee/@item.Id">
                    <input type="button" value="Delete" />
                </a>
            </td>
        </tr>
    }
</table>

Представление CreateEmployee:

@model EmployeeBase.Models.Employee

@{
    Layout = null;
}

<h2>Добавление нового сотрудника</h2>
<fieldset>
    <legend>Сотрудник</legend>
@using (Html.BeginForm())
{
    <table>
        <tr>
            <td>Name</td>
            <td>@Html.EditorFor(modelItem => modelItem.Name)</td>
        </tr>
        <tr>
            <td>Birth</td>
            <td>@Html.EditorFor(modelItem => modelItem.BirthDate)</td>
        </tr>
        <tr>
            <td>Foto</td>
            <td><input type="file" name="file"/></td>
        </tr>
        <tr>
            <td>Department</td>
            <td>@Html.DropDownListFor(modelItem => modelItem.DepartmentId, ViewBag.EmpList as SelectList)</td>
        </tr>
    </table>
    <input type="submit" value="Add" />   
}
</fieldset>

2

1 ответ 1

2

Ну загрузить изображение можно примерно так:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
    if (ModelState.IsValid)
    {
        if (file != null)
        {
            var image = new MyImage() 
            {
                MimeType = file.ContentType,
                Data = new byte[file.ContentLength]
            }  

            file.InputStream.Read(image.Data, 0, file.ContentLength); 
        }

        repository.SaveImage(image);

        return RedirectToAction("Index");
    }
    else
    {
        return View(product);
    }
}

Отображение:

 public FileContentResult GetImage(int imageId)
 {
     var image = repository.Images.FirstOrDefault(p => p.Id == imageId);

     if (image != null)
     {
         return File(image.Data, image.MimeType); 
     }
     else
       return null;
}

View:

@model YourApp.Entities.MyImage

<div class="item">

        <img src="@Url.Action("GetImage", "YourController", 
             new { Model.ID })" />
</div>

Тип представляющий изображение:

public class MyImage
{
    public int Id { get; set; }
    public byte[] Data { get; set; }
    public string MimeType { get; set; } 
}
2
  • зачем проверка на null, если у тебя FirstOrDefault
    – Lofectr
    1 янв 2021 в 6:31
  • И что не так? FirstOrDefault может вернуть null, если ничего найдено не будет.
    – sp7
    2 янв 2021 в 12:04

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.