万企互联-专注高端网站建设
扫描关注万企互联微信公众账号

扫一扫微信二维码

asp.net上传图片至数据库再显示的方法

程序设计2012/6/3 1229

在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();
        }

文章分类
程序设计
打开微信,点击底部的“发现”,使用“扫一扫”即可将网页分享至朋友圈。
万企互联 咸阳网站建设 咸阳微信营销 IDC主机测评 IP地址查询 万企工具 四六互联 四六技术网 品多技术网 超越彼岸BEYOND 六佰号 秦川云 秦川云影院