在VBA中将文件读取为字符串

时间:2017-03-13 16:15:15

标签: vba word-vba

我正在处理一个将使用HTTP帖子将文件上传到服务器的子程序。我已经计算出实际发送帖子请求的所有代码,但我无法弄清楚如何将文件转换为适当的格式。服务器期望文件的字节为字符串,但无论采用何种方法创建字符串,值都不符合预期的值。

以下是我目前的代码:

Sub Test()
    Dim FileNum As Integer
    Dim TestString As String
    Dim TestBytes() As Byte
    Dim TestByte As Variant

    FileNum = FreeFile
    Open ActiveDocument.Path & "\" & ActiveDocument.name For Binary Access Read As #FileNum    'Open document to write to string
    ReDim TestBytes(LOF(FileNum) - 1)
    Get FileNum, , TestBytes
    Close FileNum
    For Each TestByte In TestBytes
        TestString = TestString & Hex(TestByte)
    Next TestByte
    Debug.Print TestString
End Sub

输出看起来像这样(截断,因为完整的字符串显然很长):

504B3414060800021076DD8E8C9D130825B436F6E74656E745F54797065735D2E786D6C20...

问题是,示例输出我说它应该看起来像这样:

UEsDBBQABgAIAAAAIQCuTjGvewEAAAIGAAATAAgCW0NvbnRlbnRfVHlwZXNdLnhtbCCiBAIooAACA...

我认为问题是我的测试代码试图将字节编码为十六进制值,而示例显然不是十六进制,但是当我只是尝试将文件的字节直接输出为字符串时得到很多无效的字符。这是代码:

Sub Test()
    Dim FileNum As Integer
    Dim TestString As String
    Dim TestBytes() As Byte
    Dim TestByte As Variant

    FileNum = FreeFile
    Open ActiveDocument.Path & "\" & ActiveDocument.name For Binary Access Read As #FileNum    'Open document to write to string
    TestString = String$(LOF(FileNum), Chr(32))    'Fill string with blank space to set string length
    Get FileNum, , TestString   'Write binary data from file to string
    Debug.Print TestString
End Sub

这是输出:

PK     ! vÝŽŒ  p    ...

对于如何编码字节以获得与示例输出编码相同的输出,我是否遗漏了一些东西?当用另一种语言(例如使用readFileToString的Java)执行类似操作时,字符串是如何编码的?

1 个答案:

答案 0 :(得分:1)

在上面的评论中使用Alex K。的建议,以及Base64编码函数found here,我找到了这个解决方案:

	<script src="http://cdn.alloyui.com/2.0.0/aui/aui-min.js"></script>
	<link href="http://cdn.alloyui.com/2.0.0/aui-css/css/bootstrap.min.css" rel="stylesheet"></link>
	<br />
	<button id="button">call <code>changeRequest()</code></button>

哪个输出正确的字符串:

Sub Test()
    Dim FileNum As Integer
    Dim TestString As String
    Dim TestBytes() As Byte
    Dim TestByte As Variant

    FileNum = FreeFile
    Open ActiveDocument.Path & "\" & ActiveDocument.name For Binary Access Read As #FileNum    'Open document to write to string
    TestString = String$(LOF(FileNum), Chr(32))    'Fill string with blank space to set string length
    Get FileNum, , TestString   'Write binary data from file to string
    TestString = EncodeBase64(TestString)

    Debug.Print TestString
End Sub

Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)

  Dim objXML As MSXML2.DOMDocument
  Dim objNode As MSXML2.IXMLDOMElement

  Set objXML = New MSXML2.DOMDocument
  Set objNode = objXML.createElement("b64")

  objNode.DataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = objNode.text

  Set objNode = Nothing
  Set objXML = Nothing
End Function