.Net中保存和读取数据库中Image类型(二进制)字段

来源:互联网 发布:极光网络有魔戒世界吗 编辑:程序博客网 时间:2024/06/10 01:09

保存入数据库           采用参数的方式传进去    

 SqlCommand myCommand =

new SqlCommand(sql, new SqlConnection(Configuration.ConnectionString));

                sql = @"update *** set imgicc=@imgicc where Imgfno = '" + formNo + "' and Imgwno = '" + workNo + "'";

 

                FileInfo iccinfo = new FileInfo(hidden_imgicc.Value);

                myCommand.Parameters.Add("@imgicc", SqlDbType.Image, (int)iccinfo.Length);

                byte[] contenticc = new byte[iccinfo.Length];

                FileStream stream = iccinfo.OpenRead();

                stream.Read(contenticc, 0, contenticc.Length);

                stream.Close();

                myCommand.Parameters["@imgicc"].Value = contenticc;

                myCommand.CommandText = sql;

                myCommand.Connection.Open();

                myCommand.ExecuteNonQuery();

                myCommand.Connection.Close();

 

读取到页面   使用WriteLocalImage方法

  if (dsImg.Tables[0].Rows[0]["imgiccPath"] != null)

                    {

                        WriteLocalImage(dsImg.Tables[0].Rows[0]["imgiccPath"].ToString());

                    }

                    else

                    {

                        WriteNoImg();

                    }

 

private void WriteBinaryImage(byte[] img)

    {

        Response.Clear();

        Response.ContentType = "image/jpeg";

        try

        {

            Response.BinaryWrite(img);

        }

        catch

        {

            WriteNoImg();

        }

    }

 

    private void WriteLocalImage(string path)

    {

        if (path.Trim() != string.Empty)

        {

            Response.Clear();

            Response.ContentType = "image/jpeg";

            Response.TransmitFile(path);

        }

        else

        {

            WriteNoImg();

        }

    }

 

    private void WriteNoImg()

    {

        Response.Write("Image is not exists.");

    }

原创粉丝点击