上传图片至数据库再显示方法(MSSQL和MYSQL)

对于把图片上传至数据库的一点经验总结(MSSQL    MYSQL)

  在MSSQL中   图片字读类型是IMAGE   但是在MYSQL中不存在IMAGE  ,而有的提到是用BOLB类型保存,我但建议是用LONGBOLB,因为在图片稍微较大时,用BOLB保存的图片只能显示半节。下面是具体的代码

上传部分

 int len = FileUpload1.PostedFile.ContentLength;
        byte[] pic = new byte[len];
        FileUpload1.PostedFile.InputStream.Read(pic, 0, len);
        string strImageType = FileUpload1.PostedFile.ContentType;
        MySqlConnection connection = DAL.DBHelp.Conn();

        // SqlConnection connection = new
        //SqlConnection(@"server=ALLEN/SQLEXPRESS;Initial Catalog=GibbsCAMCert;Integrated Security=True");
        try
        {
            //  connection.Open();
            //   SqlCommand cmd = new SqlCommand("insert into photo "
            ///     + "(photo, type) values (@pic, @text)", connection);         
            string sql = "update tbl_resume set c_photo=?c_photo where c_uid='aaa111'";//, connection
            MySqlCommand cmd = new MySqlCommand();
            cmd.Connection = connection;
            cmd.CommandText = sql;
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("?c_photo", pic);//.Paramters.AddWithValue();

            string ss = cmd.CommandText;
            cmd.ExecuteNonQuery();

            //cmd.Parameters.Add("@pic", pic);
            //cmd.Parameters.Add("@text", strImageType);
            //cmd.ExecuteNonQuery();
        }
        finally
        {
            connection.Close();
        }

注:如果是测试直接用

   MySqlCommand cmd = new MySqlCommand("update tbl_resume set c_photo='"+pic+"' where c_uid='aaa111'",connection);这样存在数据库的大小会比图片实际字节小,读取的时候会显示不了(呵呵,具体哪出错了还没来的急研究,但我在调试的时候就因为这样郁闷了很久)

 

显示代码

 MemoryStream stream = new MemoryStream();
        //  SqlConnection connection = new SqlConnection(@"server=ALLEN/SQLEXPRESS;Initial Catalog=GibbsCAMCert;Integrated Security=True");
        MySqlConnection connection = DAL.DBHelp.Conn();
        try
        {
            //connection.Open();
            //  SqlCommand command = new SqlCommand("select photo from photo", connection);

            MySqlCommand command = new MySqlCommand("select c_photo from tbl_resume where c_uid='aaa111'", connection);

            byte[] image = (byte[])command.ExecuteScalar();
            stream.Write(image, 0, image.Length);
            Bitmap bitmap = new Bitmap(stream);
            Response.ContentType = "image/gif";
            bitmap.Save(Response.OutputStream, ImageFormat.Gif);
        }
        finally
        {
            connection.Close();
            stream.Close();
        }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值