引用如下命名空间:
using System.Drawing;
using System.IO;
using System.Data.SqlClient;
设计数据库时,表中相应的字段类型为iamge
保存:
string strPath = this.FileUpload1.PostedFile.FileName.ToString ();
FileStream fs =
new
System.IO.FileStream(strPath, FileMode.Open, FileAccess.Read);
BinaryReader br =
new
BinaryReader(fs);
byte[] photo = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
SqlConnection myConn =
new
SqlConnection(
"Data Source=.;Initial Catalog=stumanage;User ID=sa;Password=123"
);
string strComm =
" INSERT INTO stuInfo(stuid,stuimage) VALUES(107,@photoBinary )"
;
SqlCommand myComm =
new
SqlCommand(strComm, myConn);
myComm.Parameters.Add(
"@photoBinary"
, SqlDbType.Binary, photo.Length);
myComm.Parameters[
"@photoBinary"
].Value = photo;
myConn.Open();
if
(myComm.ExecuteNonQuery() > 0)
{
this.Label1.Text =
"ok"
;
}
myConn.Close();
读取:
...连接数据库字符串省略
mycon.Open();
SqlCommand command =
new
SqlCommand(
"select stuimage from stuInfo where stuid=107"
, mycon);
byte[] image = (byte[])command.ExecuteScalar ();
string strPath =
"~/Upload/zhangsan.JPG"
;
string strPhotoPath = Server.MapPath(strPath);
BinaryWriter bw =
new
BinaryWriter(File.Open(strPhotoPath,FileMode.OpenOrCreate));
bw.Write(image);
bw.Close();
this.Image1.ImageUrl = strPath;