从网上看到这段代码,非常经典实用,要做文档加密管理的朋友可以获得不少灵感。
方法一:
最好把整个Word文档保存到数据库,这样就不会丢失Wrod中的格式及所有其它的一些内容。
完整的代码如下:如果是用SQL那么保存文件的字段类型应该是Binary。如果是用Access,那么保存文件的字段应该用OLD对象,在表中显示为长二进制数据。
'将任何文件从数据库中下载到本地:
Public Function LoadFile(ByVal col As ADODB.Field, ByVal FileName As String) As Boolean '获得binary数据
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
'将文件从本地上传到数据库中
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
方法二:
数据库字段:wjmc 文件名,wjsx 文件的扩展名。Wjnr 文件的内容为二进制。(若access数据库为“ole对象”,sql server为“image”)
该程序可以操作所有的文件类型。
Dim Wenjian As String
Dim RD As Byte
Dim SIZE As Long
Const MYSIZE = 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为文件的名称加扩展名
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