字段名
类型
备注
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)
}
}
}
不过需要提的一点,如果把大量的文件存入数据库的话,会造成数据库的臃肿,而且访问量也会增大。所以现在比较流行的做法,是把文件上传到服务器上,而在数据库上只保存文件的相对路径即可。那么访问的时候,先通过数据库得到文件的相对路径,然后再访问服务器上的文件
给你提供个ACCESS版的VB代码,使用时调用这些过程即可:'使用ADODB.Stream来保存/读取图像文件到数据库
'引用Microsoft ActiveX Data Objects 2.5 Library及以上版本
'保存文件到数据库中
Sub SaveFile()
Dim Stm As New ADODB.Stream
Dim Cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strCnn As String
strCnn = "Provider=Microsoft.Jet.OLEDB.4.0Persist Security Info=FalseData Source=" &_
App.Path &"\DB1.mdb"
Cnn.Open strCnn
'读取文件到内存(二进制模式)
With Stm
.Type = adTypeBinary
.Open
.LoadFromFile App.Path + "\Image1.bmp"
End With
With rs
.Open "SELECT * FROM TABLE1", Cnn, 1, 3
.AddNew
.Fields("IMAGE") = Stm.Read
.Update
End With
rs.Close
Stm.Close
Set rs = Nothing
Set Cnn = Nothing
Set Stm = Nothing
End Sub
'从数据库中读取图像文件
Sub ReadFile()
Dim Stm As New ADODB.Stream
Dim Cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strCnn As String
strCnn = "Provider=Microsoft.Jet.OLEDB.4.0Persist Security Info=FalseData Source=" &_
App.Path &"\DB1.mdb"
Cnn.Open strCnn
rs.Open "SELECT IMAGE FROM TABLE1 WHERE ID = 18", Cnn, adOpenKeyset, adLockReadOnly
'保存到文件
With Stm
.Mode = adModeReadWrite
.Type = adTypeBinary
.Open
.Write rs("IMAGE")
.SaveToFile App.Path + "\Image2.bmp"
End With
'显示图片
Picture1.Picture = LoadPicture(App.Path + "\Image2.bmp")
rs.Close
Stm.Close
Set rs = Nothing
Set Cnn = Nothing
Set Stm = Nothing
End Sub
比较复杂,看我的笔记。根本方法是定义图片VARIANT变量,其类型为VT_ARRAY|VT_UI1。此时VARIANT的值为SAFEARRAY.将图片载入SAFEARRAY中。便可以存入图片了。可以存储任何格式 的图片
void CDataBase16Dlg::OnBnClickedAddNew()
{
CString filepath
CFileDialog filedialog(TRUE)
if(filedialog.DoModal()==IDOK)
{
filepath=filedialog.GetPathName()
}
CFile file
file.Open(filepath,CFile::modeRead)
SAFEARRAY *psa //SAFEARRAY是variant变量的参数之一。
SAFEARRAYBOUND bound[1]//SAFEARRAYBOUND为SAFEARRAY结构成员之一。
bound[0].lLbound=0 //代表数组起始索引,一般为 0
bound[0].cElements=file.GetLength() //代表元素个数,即图片的大小。以字节为单位
psa=SafeArrayCreate(VT_UI1,1,bound) //创建SAFEARRAY,中间参数代表创建的是一个一维数组
BYTE *filebuffer=new BYTE[file.GetLength()+1]
file.Read(filebuffer,file.GetLength()) //将图片文件读入内存。
for(long index=0index<file.GetLength()index++)
SafeArrayPutElement(psa,&index,&filebuffer[index]) //将图片的每一字节放入SAFEAWWAY中。
VARIANT vt
vt.vt = VT_ARRAY|VT_UI1
vt.parray=psa
m_recordset->GetFields()->GetItem(_variant_t("肖像"))->AppendChunk(vt)//添加图片。
m_recordset->Update()
}
至于读取,你没问我也就不答了,比较长。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)