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

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

代码如下:

<body> <form runat="server"> <h2>上传图片</h2> <div> <asp:FileUpload runat="server" /> <asp:Button runat="server" Text="提交" /> <asp:Label runat="server" Text="Label"></asp:Label> </div> <h2>展示图片</h2> <div> <asp:Button runat="server" Text="展示图片" /> <asp:Panel runat="server"></asp:Panel> </div> </form> </body>

效果图如下:

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

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]

数据库生成结果图:

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

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 = "图片上传失败"; } }

运行结果:

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

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); } }

运行结果:

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

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdswzx.html