代码改变世界

图片的数据库存取

2014-06-22 16:51  P.C ++  阅读(194)  评论(0编辑  收藏  举报

  SQL Server数据库里图片以二进制格式的image类型存储,存入时先转换成二进制数据,取出时由二进制转换成image/jpg格式才能显示

存入:

视图代码,需要一个上传文件的控件

@using (Html.BeginForm("Index", "NewImg", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    if (@ViewBag.ImgId != null)
    {
        <img src="@Url.Action("ShowImg", "Image", new { id = ViewBag.ImgId })" width="111" height="111" alt="img" />
        <br />
        <br />
    }
    <input type="file" name="imgUserProfile" id="imgUserProfile" />
    <br />
    <br />
    <input type="submit" value="upload img" />
}

在控制器中,接收到传入的图片文件,以byte类型存入数据库

        public ActionResult Index(HttpPostedFileBase imgUserProfile)
        {
            try
            {
                using (var context = new newpicEntities())
                {
                    var imgData = new pict1();//
                    var imgLength = imgUserProfile.ContentLength;

                    var imgByte = new byte[imgLength];

                    imgUserProfile.InputStream.Read(imgByte, 0, imgLength);

                    imgData.pict = imgByte;

                    context.AddTopict1(imgData);
                    context.SaveChanges();
                    ViewBag.ImgId = imgData.id;
                    ViewBag.Result = "success";
                }
            }
            catch (Exception e)
            {
                ViewBag.Result = e;
            }
            return View("Index");
        }

读取并显示数据库中图片:

控制器

        public ActionResult ShowImg(int id)
        {
            var image = (from m in db.pict1
                         where m.id == id
                         select m.pict).FirstOrDefault();
            var stream = new MemoryStream(image.ToArray());
            return new FileStreamResult(stream, "image/jpg");
        }

视图

<img src="@Url.Action("ShowImg","Image",new{id= item.id})" height="117px" width="144px" alt=""/>