備忘です
Option Explicit
Sub UploadFile()
Const strURL As String = "http://127.0.0.1:5000/upload"
Const strFile As String = "C:\path\to\your\file.jpg"
Dim objHTTP As Object
Dim objFSO As Object
Dim objFile As Object
Dim strBoundary As String
Dim strBody As String
Dim arrBytes() As Byte
Dim lngBytes As Long
' Random boundary string
strBoundary = "---------------------------" & Replace(Replace(Replace(Now(), ":", ""), "-", ""), " ", "")
' Read the file data into a byte array
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strFile)
lngBytes = objFile.Size
ReDim arrBytes(lngBytes)
With objFile.OpenAsTextStream(1, -2)
.Read lngBytes
.Close
End With
' Create the request body
strBody = BuildRequestBody(strBoundary, "example", strFile, arrBytes, lngBytes)
' Send the request
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP.6.0")
With objHTTP
.Open "POST", strURL, False
.setRequestHeader "Content-Type", "multipart/form-data; boundary=" & strBoundary
.send strBody
Debug.Print .Status & " " & .statusText
Debug.Print .responseText
End With
End Sub
Function BuildRequestBody(ByVal strBoundary As String, ByVal strFileField As String, ByVal strFile As String, ByRef arrBytes() As Byte, ByVal lngBytes As Long) As String
Dim strCrLf As String
Dim strHeader As String
Dim strFooter As String
Dim binaryData As String
Dim objStream As Object
strCrLf = vbCrLf
strHeader = "--" & strBoundary & strCrLf & _
"Content-Disposition: form-data; name=""" & strFileField & """; filename=""" & Mid(strFile, InStrRev(strFile, "\") + 1) & """" & strCrLf & _
"Content-Type: application/octet-stream" & strCrLf & strCrLf
strFooter = strCrLf & "--" & strBoundary & "--" & strCrLf
Set objStream = CreateObject("ADODB.Stream")
objStream.Type = 1 ' adTypeBinary
objStream.Open
objStream.Write arrBytes
objStream.Position = 0
objStream.Type
objStream.Type = 2 ' adTypeText
objStream.Charset = "iso-8859-1"
binaryData = objStream.ReadText
objStream.Close
' Combine the header, binary data, and footer to create the request body
BuildRequestBody = strHeader & binaryData & strFooter
End Function