您的当前位置:首页正文

ASP.NET实现图片以二进制的形式存入数据库

2024-11-19 来源:个人技术集锦
USE [niunantest] 
GO 
/****** 对象: Table [dbo].[picdata]  脚本日期: 03/30/2010 14:51:58 ******/ 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
CREATE TABLE [dbo].[picdata]( 
  [id] [int] IDENTITY(1,1) NOT NULL, 
  [content] [image] NULL, 
  [createdate] [datetime] NOT NULL CONSTRAINT [DF_picdata_createdate] DEFAULT (getdate()), 
 CONSTRAINT [PK_picdata] 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] 

int len = fu.PostedFile.ContentLength; // 图片大小 
byte[] pic = new byte[len]; // 创建一个字节数组,大小为图片的大小,数据库中就存储这个东西 
fu.PostedFile.InputStream.Read(pic, 0, len); // 把上传控件中的文件用二进制读取存到pic字节数组中 
//  插入图片到数据库中    
SqlConnection connection = new 
SqlConnection(@"server=.\sqlexpress;database=niunantest;uid=sa;pwd=123456"); 
try 
{ 
  connection.Open(); 
  SqlCommand cmd = new SqlCommand("insert  into  picdata  " 
  + "([content])  values  (@pic)", connection); 
  cmd.Parameters.Add("@pic", pic); 
  cmd.ExecuteNonQuery(); 
  Label1.Text = "图片插入数据库成功!"; 
 
  Image1.ImageUrl = "getpic.ashx?t=" + DateTime.Now.Ticks; // 显示刚刚插入数据库的图片 
} 
finally 
{ 
  connection.Close(); 
}  
 

MemoryStream stream = new MemoryStream(); 
SqlConnection connection = new 
SqlConnection(@"server=.\sqlexpress;database=niunantest;uid=sa;pwd=123456"); 
try 
{ 
  connection.Open(); 
  SqlCommand command = new 
  SqlCommand("select top 1 [content]  from  picdata order by id desc", connection); 
  byte[] image = (byte[])command.ExecuteScalar(); 
  stream.Write(image, 0, image.Length); 
  Bitmap bitmap = new Bitmap(stream); 
  context.Response.ContentType = "image/jpeg"; 
  bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); 
} 
finally 
{ 
  connection.Close(); 
  stream.Close(); 
}

显示全文