asp.net实现存储和读取数据库图片

时间:2022-04-27 17:06:40

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

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

代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<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>

效果图如下:

asp.net实现存储和读取数据库图片

2. 创建数据库

数据库脚本如下:

?
1
2
3
4
5
6
7
8
9
10
11
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]

数据库生成结果图:

asp.net实现存储和读取数据库图片

3.使用EF实现图片存储

实现代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 = "图片上传失败";
      }
    }

运行结果:

asp.net实现存储和读取数据库图片

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

实现代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
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);
 
      }
    }

运行结果:

asp.net实现存储和读取数据库图片

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/merciaMA/article/details/102928045