Downloaded file with Excel VBA is corrupted

Viewed 386

My Excel VBA macro sends a POST multipart/form-data request to an API and receives a application/pdf file as a response.

This is the relevant part:

Set xhr = CreateObject("MSXML2.XMLHTTP")
xhr.Open "POST", Uri, False
xhr.setRequestHeader "Content-Type", "multipart/form-data; boundary=" & strBoundary
xhr.setRequestHeader "X-Api-Key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
xhr.send (strBody)
If xhr.Status Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write xhr.responseBody
    oStream.SaveToFile outputFileName, 2
    oStream.Close
End If
Set xhr = Nothing

The downloaded PDF document is unreadable by any PDF reader. I checked its contents and it is almost the same as the downloaded document from other clients (eg Postman, cURL), which are valid PDF documents (ie can be open in PDF readers) [Edited].

For example, when opening the PDF documents in VS Code:

The VBA macro downloaded file:

enter image description here

Compare it to the PDF downloaded with Postman (Check the last line in the picture):

enter image description here

If it was a text file, it would seem as an encoding problem, but as I am using the ADODB.Stream with Type = 1 that should handle binary files well.

What am I missing?

0 Answers
Related