1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| Public Function extractAttachment(strFileName, strXPath, strOutputFolder, RequestId)
Dim iFile As Long 'binary file number index
Dim oNode As IXMLDOMNode 'base64 data node from form field
Dim nodeValue() As Byte 'full byte array of base64 data
Dim fileContent() As Byte 'byte array of file data only
Dim arrFileNameSize(4) As Byte 'byte array of file size only
Dim arrFileName() As Byte 'byte array of filename only
Dim arrFileData() As Byte
Dim oDoc As DOMDocument 'XML document object to load form into
Dim i As Long
Dim fileNameSize As Long, headerLength As Long, fileDataLength As Long
Dim strOutputFileName As String
On Error GoTo ErrHandler
'create XML document in memory
Set oDoc = New DOMDocument
'load form into XML document in memory
If oDoc.Load(strFileName) = True Then
If Not (oDoc Is Nothing) Then
'read attachment node value to oNode object
Set oNode = oDoc.documentElement.selectSingleNode(strXPath)
'typecast the node to base64 as Infopath doesn't do this in node definition
oNode.DataType = "bin.base64"
'convert base64 node value to binary and store in nodeValue byte array
nodeValue = oNode.nodeTypedValue
'read filesize from byte position 20 (4 bytes) to byte array
For i = 20 To 24
arrFileNameSize(i - 20) = nodeValue(i)
Next
'convert filesize byte array to actual file length (and multiply by 2 to get length in bytes)
fileNameSize = ByteArraytoLong(arrFileNameSize) * 2
'now we know how many bytes the filename is read in filename bytes in filename byte array
'(filename starts at 24 and goes for filesize*2 bytes)
ReDim arrFileName(fileNameSize - 1)
For i = 24 To 23 + fileNameSize
arrFileName(i - 24) = nodeValue(i)
Next
'convert filename byte array to filename string (vba takes care of typecasting here)
strFileName = Trim(arrFileName)
'calculate filecontent byte length (equals full byte size of field - header data (default and filename))
headerLength = 24 + fileNameSize
fileDataLength = UBound(nodeValue) - headerLength
'now make room in fileData byte array equal to this size
ReDim arrFileData(fileDataLength)
'store the byte data for the file in the fileData byte array
For i = headerLength To UBound(nodeValue)
arrFileData(i - headerLength) = nodeValue(i)
Next
'open up output binary file
iFile = FreeFile()
strOutputFileName = strOutputFolder & RequestId & ".xls"
Open strOutputFileName For Binary Access Write As iFile
'output entire fileContent byte array to file
Put iFile, , arrFileData
Close iFile
End If
End If
extractAttachment = True
finish:
Set oDoc = Nothing
Set oNode = Nothing
Exit Function
ErrHandler:
LogWriter LogFile, String(3, "!") & " [" & Err.Source & "] ERROR : ExtractAttachement - id : " & RequestId
extractAttachment = False
GoTo finish
End Function |
Partager