日期:2014-05-18  浏览次数:20484 次

怎樣將圖片保存到數據庫中,并顯示出來?在線等啊.....
用二進制流怎樣存取?

------解决方案--------------------
/// <summary>
/// 保存图片到数据库
/// </summary>
/// <param name= "inputFile ">
/// HtmlInputFile控件名
/// </param>
/// <param name= "tableName ">
/// tableName插入的表名
/// </param>
/// <param name= "iamgeInfromation ">
/// iamgeInfromation图片的信息介绍length <=255byte
/// </param>
public void saveImage(HtmlInputFile inputFile,string tableName,string imageInfromation)
{
HttpPostedFile upFile = inputFile.PostedFile;//HttpPostedFile对象,用来读取上传图片的属性
int fileLength = upFile.ContentLength;//记录文件的长度
try
{
if (fileLength != 0)//当文件长度不为0的时候
{
byte[] fileByte = new byte[fileLength];//用图片的长度来初始化一个字节数组存储临时的图片文件
Stream fileStream = upFile.InputStream;//建立文件流对象
fileStream.Read(fileByte, 0, fileLength);//读取图片数据到临时存储体fileByte,0为数据指针位置,fileLength为数据长度
DataBase dBase = new DataBase();
SqlCommand comm = new SqlCommand( "insert into " + tableName + "(imageData,imageContentType,imageDescription,imageSize) values ( @imageData,@imageContentType,@imageDescription,@imageSize) ", dBase.conn);//插入数据库语句
comm.Parameters.Add(new SqlParameter( "@imageData ", SqlDbType.Image));//添加参数
comm.Parameters[ "@imageData "].Value = fileByte;//给参数赋值
comm.Parameters.Add(new SqlParameter( "@imageContentType ", SqlDbType.NVarChar, 50));
comm.Parameters[ "@imageContentType "].Value = upFile.ContentType;//记录图片类型
comm.Parameters.Add(new SqlParameter( "@imageDescription ", SqlDbType.NVarChar, 255));
comm.Parameters[ "@imageDescription "].Value = imageInfromation;//把其他的表单数据上传
comm.Parameters.Add(new SqlParameter( "@imageSize ", SqlDbType.Int, 8));
comm.Parameters[ "@imageSize "].Value = upFile.ContentLength;//记录图片长度,读取数据的时候使用
dBase.conn.Open();//打开数据库连接
comm.ExecuteNonQuery();//添加数据
dBase.conn.Close();//关闭数据库
}
else
{
throw( "请选择要上传的文件! ");
}
}
catch (Exception e)
{
throw (e);
}
}
------解决方案--------------------
读取````````````

private void Writeimg()
{
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
SqlCommand cmd = new SqlCommand( "select * from img ",conn);
SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
try
{
// Response.Write( " <p> <table> <tr> ");
while(dr.Read())
{
// Response.Write( " <td> ");
byte[] by = new byte[Convert.ToInt32(dr[ "imgsize "])];
by = (byte[])dr[ "img "];
// Response.AddHeader( "Content-Type ",dr[ "imgtype "].ToString());
// Response.BinaryWrite(by);
Response.OutputStream.Write(by,0,Convert.ToInt32(dr[ "imgsize "]));
// Response.Write( " </td> ");
}
// Response.Write( " </tr> </table> </p> ");
dr.Close(