以前都是用图片路径的形式来上传到服务器然后读取的,这次就想用二进制来试试。搞了一整天,还是在询问了不少人的情况下才搞清楚。下面就详细说下实现过程吧。
首先将图片转换为二进制存,同样适用的FileUpload控件,你也可以直接使用文件的路径和名字
string fileNameNo = Path.GetFullPath(FileUpload1.PostedFile.FileName);//获取文件名和扩展名
FileStream fs = new FileStream(fileNameNo, FileMode.Open, FileAccess.Read);//创建FileStream对象,用于向BinaryReader写入字节数据流
BinaryReader br = new BinaryReader(fs);//创建BinaryReader对象,用于写入下面的byte数组
byte[] photo = br.ReadBytes((int)fs.Length); //新建byte数组,写入br中的数据
br.Close();//记得要关闭br
fs.Close();//还有fs
//然后存储到数据库中去
string sql = "update [byteimg] set Img= @photo where ID='1'";
SqlConnection connection = new SqlConnection();
connection.ConnectionString = "Data Source=.;Initial Catalog=TempTest;User ID=sa;Password=Lwh.12345";
//实例化Command对象
SqlCommand command = new SqlCommand(sql, connection);
SqlParameter sp = new SqlParameter("@photo", photo);
command.Parameters.Add(sp);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
//最后就是把数据库中的二进制取出来,然后转换为图片
protected void Button2_Click(object sender, EventArgs e)
{
DataTable dt = pub.GetDataTable("select * from [byteimg]", slocal);//这个就是一个很简单的查询得到表的操作
byte[] imagebytes = null;
if (dt.Rows.Count > 0)
{
imagebytes = (byte[])dt.Rows[0]["Img"];
}
System.IO.FileStream fs = new System.IO.FileStream("C:\\Users\\Desktop\\test.jpg", System.IO.FileMode.OpenOrCreate);//将二进制转换成的图片存放到c盘桌面会自己创建一个test.jpg的文件中去。
fs.Write(imagebytes, 0, imagebytes.Length);
fs.Close();
fs.Dispose();
}
好了,然后点击桌面上的test.jpg文件就可以看到图片了。还有其他的展示方法,很多。反正我是没搞懂,就搞懂了这一种。