VS.C#如何向数据数据库中存入和读取图片的?
2个回答
2013-10-24
展开全部
首先,在数据库中要建立相应的字段能保存Bytes,桥销例如在SQL Server中用Image类型来定敏塌游义字段。我所用到的数据库大致结构如下:
字段名
类型
备注
FileID
Int
自增字段
FileName
Varchar(256)
FullName
Varchar(1024)
FileData
Image
然后就是写入数据库,代码如下:
FileInfo fi = new FileInfo( txtFileName.Text );// Replace with your file name
if ( fi.Exists)
{
byte[] bData = null;
int nNewFileID = 0;
// Read file data into buffer
using ( FileStream fs = fi.OpenRead() )
{
bData = new byte[fi.Length];
int nReadLength = fs.Read( bData,0, (int)(fi.Length) );
}
// Add file info into DB
string strQuery = "INSERT INTO FileInfo "
+ " ( FileName, FullName, FileData ) "
+ " VALUES "
+ " ( @FileName, @FullName, @FileData ) "衫携
+ " SELECT @@IDENTITY AS 'Identity'";
SqlCommand sqlComm = new SqlCommand( strQuery, sqlConn );
sqlComm.Parameters.Add( "@FileName", fi.Name );
sqlComm.Parameters.Add( "@FullName", fi.FullName );
sqlComm.Parameters.Add( "@FileData", bData );
// Get new file ID
SqlDataReader sqlReader = sqlComm.ExecuteReader();
if( sqlReader.Read() )
{
nNewFileID = int.Parse(sqlReader.GetValue(0).ToString());
}
sqlReader.Close();
sqlComm.Dispose();
if( nNewFileID > 0 )
{
// Add new item in list view
ListViewItem itmNew = lsvFileInfo.Items.Add( fi.Name );
itmNew.Tag = nNewFileID;
}
}
而读出的代码如下:
// Get new file name
string strFullName = dlgFBSave.SelectedPath;
if( strFullName[strFullName.Length - 1] != '\\' )
strFullName += @"\";
strFullName += lsvFileInfo.SelectedItems[0].Text;
string strQuery = "SELECT FileData FROM FileInfo "
+ " WHERE FileID = " + lsvFileInfo.SelectedItems[0].Tag.ToString();
SqlDataAdapter sqlDAdapter = new SqlDataAdapter(strQuery,sqlConn);
DataSet sqlRecordSet = new DataSet();
byte[] bData = null;
//Get file data from DB
try
{
sqlDAdapter.Fill( sqlRecordSet, "FileInfo" );
foreach( DataRow dr in sqlRecordSet.Tables["FileInfo"].Rows)
{
if( dr["FileData"] != DBNull.Value )
bData = ( byte[] )dr["FileData"];
}
}
catch(SqlException sqlErr)
{
MessageBox.Show( sqlErr.Message );
}
catch
{
MessageBox.Show( "Failed to read data from DB!" );
}
sqlRecordSet.Dispose();
sqlDAdapter.Dispose();
if( bData != null )
{
// Save file
FileInfo fi = new FileInfo( strFullName );
if( !fi.Exists )
{
//Create the file.
using (FileStream fs = fi.Create())
{
fs.Write( bData, 0, bData.Length);
}
}
else
{
//Create the file.
using (FileStream fs = fi.OpenWrite())
{
fs.Write( bData, 0, bData.Length);
}
}
}
不过需要提的一点,如果把大量的文件存入数据库的话,会造成数据库的臃肿,而且访问量也会增大。所以现在比较流行的做法,是把文件上传到服务器上,而在数据库上只保存文件的相对路径即可。那么访问的时候,先通过数据库得到文件的相对路径,然后再访问服务器上的文件
字段名
类型
备注
FileID
Int
自增字段
FileName
Varchar(256)
FullName
Varchar(1024)
FileData
Image
然后就是写入数据库,代码如下:
FileInfo fi = new FileInfo( txtFileName.Text );// Replace with your file name
if ( fi.Exists)
{
byte[] bData = null;
int nNewFileID = 0;
// Read file data into buffer
using ( FileStream fs = fi.OpenRead() )
{
bData = new byte[fi.Length];
int nReadLength = fs.Read( bData,0, (int)(fi.Length) );
}
// Add file info into DB
string strQuery = "INSERT INTO FileInfo "
+ " ( FileName, FullName, FileData ) "
+ " VALUES "
+ " ( @FileName, @FullName, @FileData ) "衫携
+ " SELECT @@IDENTITY AS 'Identity'";
SqlCommand sqlComm = new SqlCommand( strQuery, sqlConn );
sqlComm.Parameters.Add( "@FileName", fi.Name );
sqlComm.Parameters.Add( "@FullName", fi.FullName );
sqlComm.Parameters.Add( "@FileData", bData );
// Get new file ID
SqlDataReader sqlReader = sqlComm.ExecuteReader();
if( sqlReader.Read() )
{
nNewFileID = int.Parse(sqlReader.GetValue(0).ToString());
}
sqlReader.Close();
sqlComm.Dispose();
if( nNewFileID > 0 )
{
// Add new item in list view
ListViewItem itmNew = lsvFileInfo.Items.Add( fi.Name );
itmNew.Tag = nNewFileID;
}
}
而读出的代码如下:
// Get new file name
string strFullName = dlgFBSave.SelectedPath;
if( strFullName[strFullName.Length - 1] != '\\' )
strFullName += @"\";
strFullName += lsvFileInfo.SelectedItems[0].Text;
string strQuery = "SELECT FileData FROM FileInfo "
+ " WHERE FileID = " + lsvFileInfo.SelectedItems[0].Tag.ToString();
SqlDataAdapter sqlDAdapter = new SqlDataAdapter(strQuery,sqlConn);
DataSet sqlRecordSet = new DataSet();
byte[] bData = null;
//Get file data from DB
try
{
sqlDAdapter.Fill( sqlRecordSet, "FileInfo" );
foreach( DataRow dr in sqlRecordSet.Tables["FileInfo"].Rows)
{
if( dr["FileData"] != DBNull.Value )
bData = ( byte[] )dr["FileData"];
}
}
catch(SqlException sqlErr)
{
MessageBox.Show( sqlErr.Message );
}
catch
{
MessageBox.Show( "Failed to read data from DB!" );
}
sqlRecordSet.Dispose();
sqlDAdapter.Dispose();
if( bData != null )
{
// Save file
FileInfo fi = new FileInfo( strFullName );
if( !fi.Exists )
{
//Create the file.
using (FileStream fs = fi.Create())
{
fs.Write( bData, 0, bData.Length);
}
}
else
{
//Create the file.
using (FileStream fs = fi.OpenWrite())
{
fs.Write( bData, 0, bData.Length);
}
}
}
不过需要提的一点,如果把大量的文件存入数据库的话,会造成数据库的臃肿,而且访问量也会增大。所以现在比较流行的做法,是把文件上传到服务器上,而在数据库上只保存文件的相对路径即可。那么访问的时候,先通过数据库得到文件的相对路径,然后再访问服务器上的文件
推荐于2017-12-15
展开全部
写入图片部分代码:
假设图返汪姿片为 test.gif
byte [] bytes = File.ReadAllBytes(@"c:\test.gif");
SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=xxx;database=数据库名");
con.open();
SqlCommand cmd = new SqlCommand("insert into 表(图片字段) values(@image)");
cmd.Parameters.Add("@image", SqlDbType.Image).Value = bytes;
cmd.ExecuteNonQuery();
读取部分漏绝代码:
SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=xxx;database=数据库名");
con.open();
SqlCommand cmd = new SqlCommand("select 图片字段 表 where 图片编号陵陆=1");
object scalar = scmd.ExecuteScalar();
byte[] bytes=(byte[])scalar;
如果保存成文件:
File.WriteAllBytes(@"c:\read.gif",bytes);
如果要直接用网页输出:
MemoryStream ms = new MemoryStream(bytes);
Response.ContentType = "image/gif";
System.Drawing.Image image=System.Drawing.Image.FromStream(ms);
image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
Response.End();
假设图返汪姿片为 test.gif
byte [] bytes = File.ReadAllBytes(@"c:\test.gif");
SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=xxx;database=数据库名");
con.open();
SqlCommand cmd = new SqlCommand("insert into 表(图片字段) values(@image)");
cmd.Parameters.Add("@image", SqlDbType.Image).Value = bytes;
cmd.ExecuteNonQuery();
读取部分漏绝代码:
SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=xxx;database=数据库名");
con.open();
SqlCommand cmd = new SqlCommand("select 图片字段 表 where 图片编号陵陆=1");
object scalar = scmd.ExecuteScalar();
byte[] bytes=(byte[])scalar;
如果保存成文件:
File.WriteAllBytes(@"c:\read.gif",bytes);
如果要直接用网页输出:
MemoryStream ms = new MemoryStream(bytes);
Response.ContentType = "image/gif";
System.Drawing.Image image=System.Drawing.Image.FromStream(ms);
image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
Response.End();
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询