如何将图片以Image类型存储到数据库 (asp.net) 如何从数据库中读取Image类型的字段(asp.net)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dz45693/article/details/4795904

将图片以Image类型存储到数据库中,首先获取图片的流对象,然后,利通Read方法从图片文件读取二进制数据存储到字节数组。
从数据库中读取Image类型的字段,首先将数据库对应的Image类型字段存储在无符号直接数组,然后再用MemoryStream类读入图片数据 

protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            string imagePath = FileUpload1.FileName;
            string imageExtend = imagePath.Substring(imagePath.LastIndexOf(".") + 1);
            int fileLength = FileUpload1.PostedFile.ContentLength;
            byte[] data = new byte[fileLength];
            HttpPostedFile hp = FileUpload1.PostedFile;
            using (Stream sr = hp.InputStream)
            {
                sr.Read(data, 0, fileLength);
                SqlConnection con = new SqlConnection("server=.;user id=sa; pwd=123;database=db_Data");
                con.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO [Table1]([name]) VALUES(@image)", con);
                cmd.Parameters.Add("@image", SqlDbType.Image);
                cmd.Parameters["@image"].Value = data;
                cmd.ExecuteNonQuery();
                Label1.Text = "Save Succeful";
            }
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }
    }
    protected void btnLoad_Click(object sender, EventArgs e)
    {
        try
        {

            using (SqlConnection con = new SqlConnection("server=.;user id=sa; pwd=123;database=db_Data"))
            {
                SqlDataAdapter ap = new SqlDataAdapter("select top 1 * from [Table1]order by ID desc", con);
                DataSet ds = new DataSet();
                ap.Fill(ds);
                byte[] data = (byte[])ds.Tables[0].Rows[0]["name"];
                MemoryStream ms = new MemoryStream(data);
                Response.Clear();
                Response.ContentType = "image/GIF";
                Response.BinaryWrite(ms.ToArray());
                Label1.Text = "Load Succeful";
            }
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }
    }

展开阅读全文

没有更多推荐了,返回首页