Search code examples
vbaexcelhttprequestxwiki

Uploading an image to web with excel vba


I'm trying to upload an image to a REST webpage. I can do this successfully though a cURL call:

curl -u Admin:admin -T C:\temp\wikiTable.jpg http://192.168.0.35:8080/xwiki/rest/wikis/xwiki/spaces/Main/pages/WebHome/attachments/table.jpg

I'm now trying to achieve this though a HTTP Post in Excel vba but experiencing some problems. I'm currently doing this:

Const STR_BOUNDARY  As String = "---------------------------123456789abc"
Dim nFile           As Integer
Dim baBuffer()      As Byte
Dim sPostData       As String
Dim sFileName       As String
Dim sUrl            As String
sFileName =  "C:\temp\wikiTable.jpg"  
sUrl =  "http://192.168.0.35:8080/xwiki/rest/wikis/xwiki/spaces/Main/pages/WebHome/attachments/table.jpg"     
'--- 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
'-- post
Dim HTTPReq As Object
Set HTTPReq = CreateObject("WinHttp.WinHttpRequest.5.1")
HTTPReq.Option(4) = 13056
HTTPReq.Open "Post", sUrl, False
HTTPReq.SetCredentials "Admin", "admin", 0
HTTPReq.setRequestHeader "Content-Type: multipart/form-data;"
HTTPReq.send sPostData
MsgBox (HTTPReq.responseText)

For the responseText I keep getting the following error:

10.4.6 405 Method Not Allowed

The method specified in the Request-Line is not allowed for the resource 
identified by the Request-URI. The response MUST include an Allow header 
containing a list of valid methods for the requested resource.
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.6

Any ideas what I'm doing wrong here?


Solution

  • The following worked in the end:

    Private Function PostFile(sUrl As String, sFileName As String, strUserName As String, strPassword As String) As String
        Dim nFile           As Integer
        Dim baBuffer()      As Byte
        Dim sPostData       As String
    '--- read file
        Dim adoStream
        Set adoStream = CreateObject("ADODB.Stream")
        adoStream.Mode = 3          ' read write
        adoStream.Type = 1          ' adTypeBinary
        adoStream.Open
        adoStream.LoadFromFile (sFileName)
        adoStream.Position = 0
    '--- post
        Dim HTTPReq As Object
        Set HTTPReq = CreateObject("WinHttp.WinHttpRequest.5.1")
        HTTPReq.Option(4) = 13056
        HTTPReq.Open "PUT", sUrl, False
        HTTPReq.setRequestHeader "Authorization", "Basic " + Base64Encode(strUserName + ":" + strPassword)
        HTTPReq.setRequestHeader "Content-Type", "multipart/form-data"
        HTTPReq.setRequestHeader "Content-Length", adoStream.Size
        HTTPReq.send (adoStream.Read(adoStream.Size))
        pvPostFile = HTTPReq.responseText
        Set adoStream = Nothing
    End Function