如何从数据库中检索图像

时间:2014-05-11 08:37:28

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我想从数据库中检索图像并显示相同的控制器'索引'查看或其他控制器'索引'视图。我想我已成功将数据插入数据库中。这是我的代码..任何人都可以帮助我,那个动作/方法和' Html'现在,我应该写我的代码..

模型类Picture

public class Picture
{
    public int PictureId { get; set; }
    public string Name { get; set; }
    public static byte[] Image { get; set; }
}

PictureController

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Picture picture)
{
        byte[] Image;
        if (Request.Files["files"] != null)
        {
            using (var binaryReader = new BinaryReader(Request.Files["file"].InputStream))
            {
                Image = binaryReader.ReadBytes(Request.Files["files"].ContentLength);
            }
            Picture.Image = Image;
        }
        if (ModelState.IsValid)
        {
            db.Pictures.Add(picture);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(picture);
    }

Create PictureController

的观点
 @model PartialView.Models.Picture

 @{ ViewBag.Title = "Create";   }

   <h2>Create</h2>

   @using (Html.BeginForm(null, null, FormMethod.Post, 
     new { enctype = "multipart/form- data" }))
 {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
    <legend>Picture</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>
    <td>File :</td>
    <td><input type="file" name="Image" id="Image" /> </td>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>  }
<div>
   @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

插入两个数据行后的数据库表:

PictureId    Name
-------------------------
    1        Song
    2        Clothes    

1 个答案:

答案 0 :(得分:1)

要在UI中显示图像,您需要定义一个控制器操作,其返回类型为filecontentresult。以下是一个例子:

public FileContentResult getImg(int id)
{
    byte[] byteArray = DbContext.Persons.Find(id).Image;
    if (byteArray != null)
    {
        return new FileContentResult(byteArray, "image/jpeg");
    }
    else
    {
        return null;
    }
}

一旦定义了控制器操作,就可以使用以下代码行将byte []显示为视图中的图像。

<img src="@Url.Action("getImg", "Person", new { id = item.Id })" alt="Person Image" />