请问在数据库里面有一个字段image类型
我将一个图片存入数据库为什么调出来显示的时候总是显示System.Byte我的代码:
第一种和第二种方法都不行string imagename="G:/原文/"+dr["ywname"].ToString().Trim()+".tif";第一种方法:
FileStream fs = new FileStream(imagename,FileMode.Open,FileAccess.Read);
byte[] text = new byte[fs.Length];
fs.Read(text,0,(int)(fs.Length)); 第二种方法:
FileStream fs = new FileStream(imagename,FileMode.Open,FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
BufferedStream bIn = new BufferedStream(fs);
byte[] buffer = new byte[bIn.Length];
int num = 0;
int j = 0;
while(br.ReadBoolean())
{
buffer[j] = br.ReadByte();//将流中的数据存入buffer数组中 buffer中
}
bIn.Flush();
fs.Close();
bIn.Close();
br.Close();
我将一个图片存入数据库为什么调出来显示的时候总是显示System.Byte我的代码:
第一种和第二种方法都不行string imagename="G:/原文/"+dr["ywname"].ToString().Trim()+".tif";第一种方法:
FileStream fs = new FileStream(imagename,FileMode.Open,FileAccess.Read);
byte[] text = new byte[fs.Length];
fs.Read(text,0,(int)(fs.Length)); 第二种方法:
FileStream fs = new FileStream(imagename,FileMode.Open,FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
BufferedStream bIn = new BufferedStream(fs);
byte[] buffer = new byte[bIn.Length];
int num = 0;
int j = 0;
while(br.ReadBoolean())
{
buffer[j] = br.ReadByte();//将流中的数据存入buffer数组中 buffer中
}
bIn.Flush();
fs.Close();
bIn.Close();
br.Close();
http://search.csdn.net/Expert/topic/1690/1690497.xml?temp=.8733484
conn.Open();
SqlCommand cmd=new SqlCommand("insert into fuser values ('1a','1b',@i)",conn);
byte[] ib=new Byte[60000];
FileStream fs=new FileStream(@"D:\windows temp\temp\1.jpg",FileMode.Open ,FileAccess.Read );
fs.Read(ib,0,60000);
cmd.Parameters.Add("@i",SqlDbType.Image,(int)fs.Length);
cmd.Parameters["@i"].Value=ib;
cmd.ExecuteNonQuery();
conn.Close();-------------------------------------------------------
//从数据库读图片到pictureboxSqlConnection conn=new SqlConnection(@"data source=chenyuming2004\VSdotNET;uid=sa;pwd=cym;database=lhf");
conn.Open();
SqlCommand cmd=new SqlCommand("select 照片 from fuser where password='1b'",conn);
SqlDataReader reader=cmd.ExecuteReader();
reader.Read();
MemoryStream buf=new MemoryStream((byte[])reader[0]);
Image image=Image.FromStream(buf,true);
pictureBox1.Image=image;
System.IO.MemoryStream byteStream = new System.IO.MemoryStream();
this.ultpicPhoto.Image.Save(byteStream,System.Drawing.Imaging.ImageFormat.Jpeg);
Byte[] bPhotoData = byteStream.GetBuffer();
显示
System.IO.MemoryStream byteStream = new System.IO.MemoryStream(图片的字节数组);
ultpicPhoto.Image = Image.FromStream(byteStream);
怎么在Image image=Image.FromStream(buf,true);
总是提示 使用了无效的参数呢?
{
OpenFileDialog of=new OpenFileDialog();
FileStream fs;
of.Filter="Picture Files(*.jpg)|*.jpg|Bmp(*.bmp)|*.bmp|All Files(*.*)|*.*";
if(of.ShowDialog()==DialogResult.OK&&of.FileName!="")
{
fs=new FileStream(of.FileName,FileMode.Open,FileAccess.Read);
byte[] btyPic=new byte[(int)fs.Length];
fs.Read(btyPic,0,btyPic.Length);
try
{
this.ptbImage.SizeMode=PictureBoxSizeMode.Normal;
this.ptbImage.Image=Image.FromFile(of.FileName);
}
catch(Exception ImageExp)
{
MessageBox.Show(ImageExp.Message);
}
fs.Close();
System.Data.SqlClient.SqlCommand sqlUpdateCommand11=new System.Data.SqlClient.SqlCommand();
sqlUpdateCommand11.Connection = this.sqlCon;
sqlUpdateCommand11.CommandText = "Update JBDA set zp=@zp where zgbh=@zgbh";
sqlUpdateCommand11.Parameters.Add(new System.Data.SqlClient.SqlParameter("@zgbh", System.Data.SqlDbType.VarChar, 50, "zgbh"));
sqlUpdateCommand11.Parameters["@zgbh"].Value=this.txtzgbh.Text;
sqlUpdateCommand11.Parameters.Add(new System.Data.SqlClient.SqlParameter("@zp", System.Data.SqlDbType.Binary,bytPic.Length, "zp"));
sqlUpdateCommand11.Parameters["@zp"].Value=btyPic;
try{sqlUpdateCommand11.ExecuteNonQuery();}
catch(Exception exp)
{MessageBox.Show(exp.Message);}
this.sqljbda.Update(this.dsResult,"JBDA");
this.sqljbda.Fill(this.dsResult,"JBDA");
sqlUpdateCommand11.Connection.Close();
MessageBox.Show("图片插入成功");
}
/// <summary>
/// download File From Server's DB
/// </summary>
public void downloadFile(HttpRequest reqst,HttpResponse respon, HttpServerUtility server , string userId,string nodeId,string docId,string version,bool isCheckOut)
{
DataBase db = null;
System.IO.FileStream myFile = null;
//BinaryReader br = null;
respon.Clear();try
{
db= new DataBase();
db.Open();// Check the File
this.checkFileExisted( db.Connection , null , nodeId , docId , null );
}
catch( ApplicationException ex )
{
throw ex;
}
catch( Exception ex )
{
throw ex;
}
finally
{
db.Close();
}try
{
db= new DataBase();
db.Open();// DownLoad File
string sqlText = " SELECT DocName, Content ";
sqlText+= " FROM T_DMS_DOC ";
sqlText+= " WHERE NodeId ='"+DataBase.SqlItemTextChange(nodeId)+"' ";
sqlText+= " AND DocId ='"+DataBase.SqlItemTextChange(docId)+"' ";
sqlText+= " AND Version ='"+DataBase.SqlItemTextChange(version)+"' ";SqlCommand cmd=new SqlCommand(sqlText,db.Connection);
SqlDataReader rd;
// Write Log
LogManager.WriteLog("Execute "+cmd.CommandText);
rd=cmd.ExecuteReader();while(rd.Read())
{
// Orginal File Name
string fileName= rd["DocName"].ToString();// Temp File Name with server path
string ServerPath= server.MapPath("TempFile");// Delete temp , if existed
if(File.Exists(ServerPath))
{
File.Delete(ServerPath);
}// Get File from database
myFile= new System.IO.FileStream(ServerPath,System.IO.FileMode.Create);
myFile.Write(((byte[])rd["Content"]),0,((byte[])rd["Content"]).Length);#region New Source
// Write file into harddisk
StreamWriter swMyFile = new StreamWriter( myFile ) ;
swMyFile.WriteLine("") ;
swMyFile.Flush() ;
swMyFile.Close() ;
myFile.Close() ;// Get Temp File info
FileInfo fi = new FileInfo(ServerPath);// determine the name and size of the file
string filename = fi.Name;
string filesize = fi.Length.ToString();
fi = null;// clear the response, set the contenttype and the file name/size
respon.Clear();
respon.ContentType = "application/octet-stream";
respon.AppendHeader("Content-Disposition", "attachment; filename=" + server.UrlEncode(fileName) + @"");
respon.AppendHeader ("Content-Length", filesize); // flush the response, then send the file down
respon.Flush();
respon.WriteFile(ServerPath);
#endregion#region Old Source
//br = new BinaryReader(myFile);
//
////respon.Clear();
//respon.AddHeader("Accept-Ranges", "bytes");
//respon.Buffer = false;
//long fileLength = myFile.Length;
//long startBytes = 0;
//
//int pack = 10240; //10K bytes
////int sleep = 200;
//int sleep = (int)Math.Floor(1000 * pack / 1048576) + 1;
//if (reqst.Headers["Range"] != null)
//{
//respon.StatusCode = 206;
//string[] range = reqst.Headers["Range"].Split(new char[] {'=', '-'});
//startBytes = Convert.ToInt64(range[1]);
//}
//respon.AddHeader("Content-Length", (fileLength - startBytes).ToString());
//if (startBytes != 0)
//{
//respon.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
//}
//
//respon.AddHeader("Connection", "Keep-Alive");
//respon.ContentType = "application/octet-stream";
//respon.AddHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8).Replace("+"," ") );
//
//br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
//int maxCount = (int) Math.Floor((fileLength - startBytes) / pack) + 1;
//
//respon.Flush();
//
//for (int i = 0; i < maxCount; i++)
//{
//if (respon.IsClientConnected)
//{
//respon.BinaryWrite(br.ReadBytes(pack));
//Thread.Sleep(sleep);
//}
//else
//{
//i=maxCount;
//}
//}
//
//br.Close();
//myFile.Close();
#endregion
}rd.Close();
db.Close();
}
catch(ApplicationException ex)
{
throw ex;
}
catch(Exception ex)
{
throw ex;
}
finally
{
//db.Close();
respon.End();
}}/// <summary>
/// Creat New File in DB
/// </summary>
/// <param name="strNodeId"></param>
/// <param name="file"></param>
/// <param name="description"></param>
/// <param name="userId"></param>
public void creatNewFile(string strNodeId,HtmlInputFile file,string description,string userId)
{
Stream imgdatastream= file.PostedFile.InputStream;
string fileName= System.IO.Path.GetFileName(file.PostedFile.FileName).Trim();
int imgdatalen= file.PostedFile.ContentLength;
string imgtype= file.PostedFile.ContentType;
byte[] imgdata= new byte[imgdatalen];
int n= imgdatastream.Read(imgdata,0,imgdatalen);
DataBase db= new DataBase();
DataSet ds ;
db.Open();// check DB
string sqlcheck = " SELECT * FROM T_DMS_DOC ";
sqlcheck += " WHERE NodeId = '"+ DataBase.SqlItemTextChange(strNodeId) +"'";
sqlcheck += " AND DocName = '"+ DataBase.SqlItemTextChange(fileName) +"'";
sqlcheck += " AND DelStatus = 0";// not deleteddb.ExecSQL(sqlcheck,"T_DMS_DOC",out ds);if(ds.Tables.Count!= 0 && ds.Tables[0].Rows.Count !=0)
{
throw new Exception("1011");
}// Get Document ID
double randomStr = new System.Random().NextDouble()* 1000000000;
string docID = DateTime.Now.ToString("yyyyMMdd") + (Math.Floor(randomStr)).ToString();// Insert File to DB
stringsql = " INSERT INTO T_DMS_DOC (NodeId,DocId,Version,DocName,Content,Description,UpdDate,UpdUid,CheckOut,DelStatus) ";
sql += " VALUES( '"+ DataBase.SqlItemTextChange(strNodeId) +"','"+docID+"',1,'"+DataBase.SqlItemTextChange(fileName) +"',@imgdata,'"+DataBase.SqlItemTextChange(description)+"',GETDATE(),'"+DataBase.SqlItemTextChange(userId)+"',"+"'0','0')" ;SqlCommand command = new SqlCommand(sql,db.Connection );SqlParameter paramData = new SqlParameter( "@imgdata", SqlDbType.Image );
paramData.Value = imgdata;
command.Parameters.Add( paramData );try
{
//db.BeginTrans();
// Write Log
LogManager.WriteLog("Execute "+command.CommandText);int numRowsAffected = command.ExecuteNonQuery();if(numRowsAffected !=1)
{
throw new Exception("1012");
}LogManager.WriteLog("Success");//db.CommitTrans();
}
catch(Exception ex)
{
LogManager.WriteLog("Failure "+ ex.Message);
db.RollBack();
throw ex;
}
finally
{
db.Close();
}
}
How To Read and Write BLOB Data by Using ADO.NET with Visual C# .NET
http://support.microsoft.com/default.aspx?scid=kb;EN-US;309158
把任意类型的文件保存到SQL Server
http://dotnet.aspx.cc/ShowDetail.aspx?id=EY1XLDYV-PIDF-43LO-1WFL-FMY5ALE1F635