• 图片的数据库存取


      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=""/>
  • 相关阅读:
    [POJ1743]Musical Theme
    ubuntu qq
    Separate code and data contexts: an architectural approach to virtual text sharing
    Python3发送post请求,自动记住cookie
    python 异步协程
    豆瓣爬虫
    pandas 使用
    房天下爬虫
    计算英文文章词频的两种方法
    LOW版统计词频
  • 原文地址:https://www.cnblogs.com/p-c-/p/3802716.html
Copyright © 2020-2023  润新知