如何使用MVC 4从数据库显示二进制图像以编辑表单

时间:2014-01-29 03:36:08

标签: asp.net-mvc-4 binaryfiles

我将图像作为二进制图像成功存储在数据库中。 我想以编辑形式显示这些图像以修改和保存更改。 在从数据库显示二进制图像时,在Edit.cshtml表单中抛出了System.OutOfMemoryException。

有人可以更正我的代码。

模特课:

public class Accommodation
    {
        [Key]
        public string A_Unique_Id { get; set; }

        public byte[] Picture1 { get; set; }

        public byte[] Picture2 { get; set; }

        public byte[] Picture3 { get; set; }


  }

// GET:/ Accommodation / Edit / 5

public ActionResult Edit(string id)
    {
        Accommodation accommodation = db.Accommodation.Find(id);
        ViewBag.SelectedAustraliaStateId = new SelectList(db.AustraliaStates, "AustraliaStateId", "AustraliaStateName", accommodation.SelectedAustraliaStateId);

        return View(accommodation);
    }

// POST:/ Accommodation / Edit / 5

[HttpPost]
public ActionResult Edit(Accommodation accommodation)
{
    if (ModelState.IsValid)
    {
        db.Entry(accommodation).State = EntityState.Modified;

        //the following line is for re-assigning back the DDL modified value.
        accommodation.State = accommodation.SelectedAustraliaStateId;

        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(accommodation);
}

Edit.cshtml

<div class="editor-label">
        @Html.LabelFor(model => model.Picture1)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Picture1)
        @Html.ValidationMessageFor(model => model.Picture1)
    </div>

错误消息:行@Html.EditorFor(model => model.Picture1)

引发了'System.OutOfMemoryException'类型的异常

2 个答案:

答案 0 :(得分:16)

在视图中显示图像

查看

<form  method="post" enctype="multipart/form-data">
@{
    if (Model.Picture1 != null)
      {
         string imageBase64 = Convert.ToBase64String(Model.Picture1);
         string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
         <img src="@imageSrc" width="100" height="100" />
      }
  }
    <input type="file" name="photo" id="files" accept="image/*;capture=camera">
    <button type="button">Submit</button>
  </form>

控制器

[HttpPost]
public ActionResult Edit(Accommodation accommodation)
{

  if (Request.Files["files"] != null)
    {
            byte[] Image;
            using (var binaryReader = new BinaryReader(Request.Files["files"].InputStream))
            {
                Image = binaryReader.ReadBytes(Request.Files["files"].ContentLength);
            }
    }
    accommodation.Picture1=Image;
  //your code to save data
}

答案 1 :(得分:0)

byte[] imageByteData = System.IO.File.ReadAllBytes(imageFile);

string imageBase64Data = Convert.ToBase64String(imageByteData);

string imageDataURL = string.Format("data:image/jpg;base64{0}",imageBase64Data);

Session["photo"] = imageDataURL;

在_layout.cshtml页面中添加此行。