-
-
Save xxdoc/d0834a0b0d3f964cdd4ddecd5faae716 to your computer and use it in GitHub Desktop.
Send JSON and binary file as multipart request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Option Explicit | |
Private Function pvPostFile(sUrl As String, sJSON As String, sFileName As String, Optional ByVal bAsync As Boolean) As String | |
Const STR_BOUNDARY As String = "864d391d-4097-44e0-92e1-71aff17094c1" | |
Dim nFile As Integer | |
Dim baBuffer() As Byte | |
Dim sPostData As String | |
'--- read file | |
nFile = FreeFile | |
Open sFileName For Binary Access Read As nFile | |
If LOF(nFile) > 0 Then | |
ReDim baBuffer(0 To LOF(nFile) - 1) As Byte | |
Get nFile, , baBuffer | |
sPostData = StrConv(baBuffer, vbUnicode) | |
End If | |
Close nFile | |
'--- prepare body | |
sPostData = "--" & STR_BOUNDARY & vbCrLf & _ | |
"Content-Disposition: form-data; name=""json""" & vbCrLf & _ | |
"Content-Type: application/json" & vbCrLf & vbCrLf & _ | |
sJSON & vbCrLf & _ | |
"--" & STR_BOUNDARY & vbCrLf & _ | |
"Content-Disposition: form-data; name=""uploadfile""; filename=""" & Mid$(sFileName, InStrRev(sFileName, "\") + 1) & """" & vbCrLf & _ | |
"Content-Type: application/octet-stream" & vbCrLf & vbCrLf & _ | |
sPostData & vbCrLf & _ | |
"--" & STR_BOUNDARY & "--" | |
'--- post | |
With CreateObject("Microsoft.XMLHTTP") | |
.Open "POST", sUrl, bAsync | |
.SetRequestHeader "Content-Type", "multipart/form-data; boundary=" & STR_BOUNDARY | |
.Send pvToByteArray(sPostData) | |
If Not bAsync Then | |
pvPostFile = .ResponseText | |
End If | |
End With | |
End Function | |
Private Function pvToByteArray(sText As String) As Byte() | |
pvToByteArray = StrConv(sText, vbFromUnicode) | |
End Function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment