Sometimes, we need to save a word article to the database for future search and use, but how to do this? Below are two methods of storing word documents in the database.
The first method: save the entire word document to the database, which not only saves the content in the word document, but also saves the format in word.
When saving, if the database used is SQL Server, the field in which the word document is saved should use the Binary data type. If the ACCESS database is used, the OLE object should be used.
The complete source code is as follows:
'Download any file from the database to local:
Public Function LoadFile(ByVal col As ADODB.Field, ByVal FileName As String) As Boolean 'Get binary data
On Error GoTo myerr:
Dim arrBytes() As Byte
Dim FreeFileNumber As Integer
lngsize = col.ActualSize
arrBytes = col.GetChunk(lngsize)
FreeFileNumber = FreeFile
Open FileName For Binary Access Write As #FreeFileNumber
Put #FreeFileNumber, , arrBytes
Close #FreeFileNumber
LoadFile = True
myerr:
If Err.Number <> 0 Then
LoadFile = False
Err.Clear
End If
End Function
'Upload files from local to database
Public Function UpLoadFile(ByVal FileName, ByVal col As ADODB.Field) As Boolean
On Error GoTo myerr:
Dim arrBytes() As Byte
Dim FreeFileNumber As Integer
FreeFileNumber = FreeFile
Open FileName For Binary As #FreeFileNumber
n = LOF(FreeFileNumber)
ReDim arrBytes(1 To n) As Byte
Get #FreeFileNumber, , arrBytes
Close #FreeFileNumber
col.AppendChunk(arrBytes)
UpLoadFile = True
myerr:
If Err.Number <> 0 Then
UpLoadFile = False
Err.Clear
End If
End Function
Second method:
When designing the database, the design fields include: wjmc (file name), wjsx (file extension), Wjnr (file content is binary data type). (If the database uses access database, the file content is ole object, and the sql server database is image)
The program can operate on all file types.
Dim Wenjian As String
Dim RD As Byte
Dim SIZE As Long
ConstMYSIZE = 1048576
Dim WENJIANN() As Byte
Dim Rs As New ADODB.Recordset
Rs.Open select * from wj, Cn, 1, 3
Rs.AddNew
Rs!wjmc = Mid(Name, 1, InStr(Name, .) - 1)
Rs!wjsx = Mid(Name, InStr(Name, .) + 1)
'name is the name of the file plus extension
Open Filename For Binary Access Read As #1
SIZE = LOF(1)
Do While SIZE - MYSIZE >= 0
ReDim WENJIANN(MYSIZE) As Byte
Get #1, , WENJIANN
Rs!wjnr.AppendChunk WENJIANN
SIZE = SIZE - MYSIZE
Loop
If SIZE > 0 Then
ReDim WENJIANN(SIZE) As Byte
Get #1, , WENJIANN
Rs!wjnr.AppendChunk WENJIANN
End If
Close #1
Rs.Update
Set Rs=Nothing
If you need this article, bookmark it.