Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Send JSON and binary file as multipart request
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

This comment has been minimized.

Copy link

@cyberzilla cyberzilla commented Dec 8, 2019

i try this code, only max 100MB file to upload, how to upload large than 100MB, the error "Out Of String Space" error number 14


This comment has been minimized.

Copy link
Owner Author

@wqweto wqweto commented Dec 8, 2019

This simple XMLHTTP file upload code has severe limitations on the file size. For real/raw winsock implementation try

The cHttpDownload class has an UploadFile method that can be used with binary files of any size (although I didn't test the UploadProgress event for file sizes above 2GB -- might overflow).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment