vb base64 操作

'将二进制文件转换成base64编码
Public Function ConvertFileToBase64(ByVal fileName) As String
    Dim file_length As Long
    Dim fnum As Integer
    Dim bytes() As Byte
    Dim txt As String
    Dim i As Integer
    file_length = FileLen(fileName)
    fnum = FreeFile
    ReDim bytes(1 To file_length)
    Open fileName For Binary As #fnum
    Get #fnum, 1, bytes
    Close fnum
    tmp = EncodeBase64(bytes)
    ConvertFileToBase64 = tmp
End Function


Private Function EncodeBase64(ByRef arrData() As Byte) As String
    Dim objXML As MSXML2.DOMDocument
    Dim objNode As MSXML2.IXMLDOMElement
   
    ' help from MSXML
    Set objXML = New MSXML2.DOMDocument
   
    ' byte array to base64
    Set objNode = objXML.createElement("b64")
    objNode.dataType = "bin.base64"
    objNode.nodeTypedValue = arrData
    EncodeBase64 = objNode.Text
    ' thanks, bye
    Set objNode = Nothing
    Set objXML = Nothing
End Function

Private Function DecodeBase64(ByVal strData As String) As Byte()
    Dim objXML As MSXML2.DOMDocument
    Dim objNode As MSXML2.IXMLDOMElement
   
    ' help from MSXML
    Set objXML = New MSXML2.DOMDocument
    Set objNode = objXML.createElement("b64")
    objNode.dataType = "bin.base64"
    objNode.Text = strData
    DecodeBase64 = objNode.nodeTypedValue
   
    ' thanks, bye
    Set objNode = Nothing
    Set objXML = Nothing
End Function

'从base64编码过的文件还原成二进制文件
Public Function ConvertFileFromBase64(ByVal fromName As String, ByVal toName As String)
    Dim TextLine
    Open fromName For Input As #1 ' 打开文件。
    Do While Not EOF(1) ' 循环至文件尾。
        Line Input #1, TextLine ' 读入一行数据并将其赋予某变量。
    Loop
    Close #1 ' 关闭文件。
    Dim a() As Byte
   ' ReDim a(1 To Len(TextLine))
    a = DecodeBase64(TextLine)
    fnum = FreeFile
    Open toName For Binary As #fnum
    Put #fnum, 1, a
    Close fnum
End Function

'读一个文本文件
Public Function ReadTextFile(ByVal fileName As String) As String
    Dim TextLine
    Open fileName For Input As #1 ' 打开文件。
    Do While Not EOF(1) ' 循环至文件尾。
        Line Input #1, TextLine ' 读入一行数据并将其赋予某变量。
    Loop
    Close #1 ' 关闭文件。
    ReadTextFile = TextLine
End Function

 '写一个文本文件
Public Function WriteTextFile(ByVal fileName As String, ByVal strToWrite As String)
    Open fileName For Output As #fnum
    Print #fnum, strToWrite
    Close #fnum
End Function

 


 

你可能感兴趣的:(base64)