Uploading and retrieving images from SQL Server

Introduction
Some times we need to store binary data in database. SQL Server provides a special data type called image that can hold such binary data. The examples of binary data include images, documents etc. In this article we will see how we can store and retrieve images in SQL server database
Creating Tables
In order to work with the examples of this article you will need a table in some database. (You may chose to create it in existing database or create a enw database all together) Following table explains structure of the table :
Column NameDatatypePurpose
IDInteger identity column Primary key
IMGTITLEVarchar(50)Stores some user friendly title to identity the image
IMGTYPEVarchar(50)Stores image content type. This will be same as recognized content types of ASP.NET
IMGDATAImageStores actual image or binary data.
Storing images in SQL Server database

In order to store images to the table you will first upload them to your web server from the client browser. You can develop a web form that accepts image title via a TextBox web control and image file via HTML File Server Control. Make sure you set encType attribute of the Form to multipart/form-data.

Stream imgdatastream = File1.PostedFile.InputStream;
int imgdatalen = File1.PostedFile.ContentLength;
string imgtype = File1.PostedFile.ContentType;
string imgtitle = TextBox1.Text;
byte[] imgdata = new byte[imgdatalen];
int n = imgdatastream.Read(imgdata,0,imgdatalen);
string connstr=
((NameValueCollection)Context.GetConfig
("appSettings"))["connstr"];
SqlConnection connection = new SqlConnection(connstr);
SqlCommand command = new SqlCommand
("INSERT INTO ImageStore(imgtitle,imgtype,imgdata)
VALUES ( @imgtitle, @imgtype,@imgdata )", connection );

SqlParameter paramTitle = new SqlParameter
("@imgtitle", SqlDbType.VarChar,50 );
paramTitle.Value = imgtitle;
command.Parameters.Add( paramTitle);

SqlParameter paramData = new SqlParameter
( "@imgdata", SqlDbType.Image );
paramData.Value = imgdata;
command.Parameters.Add( paramData );

SqlParameter paramType = new SqlParameter
( "@imgtype", SqlDbType.VarChar,50 );
paramType.Value = imgtype;
command.Parameters.Add( paramType );

connection.Open();
int numRowsAffected = command.ExecuteNonQuery();
connection.Close();
Retrieving images from database

Now, let us read the images from the database we stored previously. Here, we will output the image directly to the browser. You can instead save it as a file or do whatever you want.

private void Page_Load(object sender, System.EventArgs e)
{
string imgid =Request.QueryString["imgid"];
string connstr=((NameValueCollection)
Context.GetConfig("appSettings"))["connstr"];
string sql="SELECT imgdata, imgtype FROM ImageStore WHERE id = "
+ imgid;
SqlConnection connection = new SqlConnection(connstr);
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if(dr.Read())
{
	Response.ContentType = dr["imgtype"].ToString();
	Response.BinaryWrite( (byte[]) dr["imgdata"] );
}
connection.Close();
}

In the above code we have opened a connection with our database. We then SELECT images via datareader. Since the image data is binary data we used Response.BinaryWrite instead of normal Response.Write.

从数据库中读出数据,并保存到文件

string ConnectionString=@"Provider=Microsoft.Jet.OLEDB.4.0;" +
     @"Password="""";User ID=Admin;Data Source=" + Application.StartupPath +
     @"/db.mdb";
    string SQL="select * from 文件";
    OleDbConnection conn=new OleDbConnection(ConnectionString);
    OleDbCommand cmd=conn.CreateCommand();
    cmd.CommandText=SQL;
    conn.Open();
    OleDbDataReader dr=cmd.ExecuteReader();

    if(dr.Read())
    {
     string strFile=string.Empty;
     strFile=dr.GetString(1);
     byte[] by=(byte[])dr.GetValue(2);

     FileStream fs=File.Open(strFile,FileMode.Create,FileAccess.Write);
     fs.Write(by,0,by.Length);
     fs.Close();
     MessageBox.Show("读取成功!");
    }
    dr.Close();
    conn.Close();
从数据库中读出图片,并保存到文件,与这是一样的实现方法。

将文件保存到数据库

string ConnectionString=@"Provider=Microsoft.Jet.OLEDB.4.0;" +
     @"Password="""";User ID=Admin;Data Source=" + Application.StartupPath +
     @"/db.mdb";
    string SQL="select * from 文件";
    OleDbConnection conn=new OleDbConnection(ConnectionString);
    OleDbDataAdapter da=new OleDbDataAdapter(SQL,conn);
    OleDbCommandBuilder cmd=new OleDbCommandBuilder(da);
    DataSet ds=new DataSet();

    conn.Open();
    da.Fill(ds,"文件");
    DataTable dt=ds.Tables[0];
    DataRow dr;
    if(dt.Rows.Count>0)
     dr=dt.Rows[0];
    else
     dr=dt.NewRow();

    dr[1]=txtFile.Text;
    FileStream fs=File.Open(txtFile.Text,FileMode.Open,FileAccess.Read);
    byte[] by=new byte[fs.Length];
    fs.Read(by,0,(int)fs.Length);
    dr[2]=by;
   
    if(dt.Rows.Count<=0)
     dt.Rows.Add(dr);
    da.Update(ds, "文件");

    conn.Close();
    fs.Close();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值