VBA 保存字节数组至文件

huangapple go评论121阅读模式
英文:

VBA Save Byte Array to File

问题

我已收到来自API的POST请求的字节数组作为响应。该字节数组是一个PDF文档。我一直在搜索,但找不到从哪里开始的地方。如果我有一个字节数组,我该如何将其保存为PDF?

抱歉,我没有代码,因为我不确定从哪里开始,是否有人能提供至少一些链接或指导,以便我可以查找如何做这个的方法?

英文:

I have received a Byte Array as response from a POST request to an API. The Byte Array is of a pdf document. I have been searching around but couldn't find where to start. If I have a byte array how would I go about saving it back as a PDF?

Apologies I have no code as I'm not sure where to start, could anyone provide with at least some links or guidance so I can look up how to do this?

答案1

得分: 1

Sub SaveByteArray(bArr() As Byte, fileName As String, Optional overWriteFile As Boolean)
  
  With CreateObject("ADODB.Stream")
    .Open
    .Type = 1
    .Write bArr
    .SaveToFile fileName, IIf(overWriteFile, 2, 1)
    .Close
  End With
  
End Sub

Sub TestSaveByteArray()
  Dim fileName As String: fileName = ThisWorkbook.Path & "\myFile.pdf"
  Dim fileToRead As String: fileToRead = "C:\your path\TestFile.pdf" 'place the path of an existing pdf file!
  Dim arr() As Byte
  'load the array (somehow...), only to have a checkable byte array:
  arr = ReadBytes(fileToRead) 'you must use your existing array instead!
  
  SaveByteArray arr, fileName, True
End Sub

Private Function ReadBytes(strFile As String) As Byte() 'only to supply a (testing) byte array...
 Dim byteArr() As Byte
 Dim frFile As Integer: frFile = FreeFile
 Open strFile For Binary Access Read As #frFile
    ReDim byteArr(0 To LOF(frFile) - 1)
    Get #frFile, , byteArr
 Close #frFile
 ReadBytes = byteArr
End Function
英文:

Please, use the next Sub:

Sub SaveByteArray(bArr() As Byte, fileName As String, Optional overWriteFile As Boolean)
  
  With CreateObject("ADODB.Stream")
    .Open
    .Type = 1
    .Write bArr
    .SaveToFile fileName, IIf(overWriteFile, 2, 1)
    .Close
  End With
  
End Sub

And use it as:

Sub TestSaveByteArray()
  Dim fileName As String: fileName = ThisWorkbook.Path & "\myFile.pdf"
  Dim fileToRead As String: fileToRead = "C:\your path\TestFile.pdf" 'place the path of an existing pdf file!
   Dim arr() As Byte
  'load the array (somehow...), only to have a checkable byte array:
  arr = ReadBytes(fileToRead) 'you must use your existing array instead!
  
  SaveByteArray arr, fileName, True
End Sub

Private Function ReadBytes(strFile As String) As Byte() 'only to supply a (testing) byte array...
 Dim byteArr() As Byte
 Dim frFile As Integer: frFile = FreeFile
 Open strFile For Binary Access Read As #frFile
    ReDim byteArr(0 To LOF(frFile) - 1)
    Get #frFile, , byteArr
 Close #frFile
 ReadBytes = byteArr
End Function

huangapple
  • 本文由 发表于 2023年8月10日 21:00:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76875966.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定