本文实例为大家分享了asp.net存储和读取数据库图片的具体代码,供大家参考,具体内容如下

1. 创建asp.net web窗体项目

代码如下:

<body>
  <form id="form1" runat="server">
    <h2>上传图片</h2>
    <div>
      <asp:FileUpload ID="ful_image" runat="server" />
      <asp:Button ID="btn_submit" runat="server" Text="提交" />
       <asp:Label ID="lbl_message" runat="server" Text="Label"></asp:Label>
    </div>
     <h2>展示图片</h2>
    <div>
      <asp:Button ID="btn_show" runat="server" Text="展示图片" />
      <asp:Panel ID="pn_images" runat="server"></asp:Panel>
    </div>
  </form>
</body>

效果图如下:

2. 创建数据库

数据库脚本如下:

create database Imagetest
 go
 use Imagetest
 CREATE TABLE [dbo].[imageTable](
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [imageData] [image] NULL,
 CONSTRAINT [PK_imageTable] PRIMARY KEY CLUSTERED 
(
 [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

数据库生成结果图:

3.使用EF实现图片存储

实现代码:

protected void btn_submit_Click(object sender, EventArgs e)
    {
      ImagetestEntities ie = new ImagetestEntities();
      imageTable it = new imageTable();
      it.imageData = ful_image.FileBytes;
      it= ie.imageTables.Add(it);
      ie.SaveChanges();
      if(it.ID!=0)
      {
        lbl_message.Text = "图片上传成功";
      }
      else
      {
        lbl_message.Text = "图片上传失败";
      }
    }

运行结果:

4. 使用EF实现图片的展示

实现代码:

protected void btn_show_Click(object sender, EventArgs e)
    {
      ImagetestEntities ie = new ImagetestEntities();
      List<imageTable> list= ie.imageTables.ToList<imageTable>();
      foreach (imageTable item in list)
      {
        Image img = new Image();
        img.ImageUrl ="data:image/png;base64,"+ Convert.ToBase64String(item.imageData);
        pn_images.Controls.Add(img);

      }
    }

运行结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持阿兔在线工具。

点赞(0)

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部