zoukankan      html  css  js  c++  java
  • 图片的数据库存取

      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=""/>
  • 相关阅读:
    callable函数,检查对象是否可调用
    eval函数的一些用法
    divmod函数使用
    sorted(x, reverse=True)
    列表、元组、字典空格的几种移除方法
    约瑟夫环问题(通过观察得出递推式从而建立递归求解)
    快速幂算法(二分思想减少连乘次数)
    素数筛(埃氏筛法与欧拉筛)
    KMP算法的详细解释
    对于线性代数的形象化理解(1)
  • 原文地址:https://www.cnblogs.com/p-c-/p/3802716.html
Copyright © 2011-2022 走看看