Skip to content

Instantly share code, notes, and snippets.

@wqweto
Created May 5, 2019 10:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save wqweto/100a0f8c7a90863a06f7b669b1eb6261 to your computer and use it in GitHub Desktop.
Save wqweto/100a0f8c7a90863a06f7b669b1eb6261 to your computer and use it in GitHub Desktop.
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
@cyberzilla
Copy link

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

@wqweto
Copy link
Author

wqweto commented Dec 8, 2019

This simple XMLHTTP file upload code has severe limitations on the file size. For real/raw winsock implementation try https://github.com/wqweto/VbAsyncSocket/blob/master/contrib/cHttpDownload.cls

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