Project

General

Profile

How to upload a file by REST API in VBA

Added by jibin lee about 7 years ago

Hi:

I follow the REST API document to upload a excel file in VBA

When I run the post upload.xml and then login the redmine server to see that the file has existed, but it's name is oddness.

Then I use the token to post issues.xml, It's failed.

My code is below:

Private Sub uploadButton1_Click()
    respText = pvPostFile("http://redmine.group.cn/redmine/uploads.xml?key=bb07446d032bba5505516cca7c115c89e7c5c25b", "d:\128393.csv", "application/octet-stream;", False)
    ThisWorkbook.Sheets(1).Cells(10, 1) = respText
    MsgBox respText
End Sub

Private Function pvPostFile(sUrl As String, sFileName As String, sContextType As String, Optional ByVal bAsync As Boolean) As String
    Const STR_BOUNDARY  As String = "3fbd04f5-b1ed-4060-99b9-fca7ff59c113" 
    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

    '--- post
    With CreateObject("Microsoft.XMLHTTP")
        .Open "POST", sUrl, bAsync
        .setRequestHeader "Content-Type", sContextType 
        .send pvToByteArray(sPostData)
        If Not bAsync Then
            pvPostFile = .Status & .responseText
        End If
    End With
End Function

Private Function pvToByteArray(sText As String) As Byte()
    pvToByteArray = StrConv(sText, vbFromUnicode)
End Function

Private Sub issueButton_Click()

    respText = pvPostFile("http://redmine.group.cn/redmine/issues.xml?key=bb07446d032bba5505516cca7c115c89e7c5c25b", "d:\issues.xml", "application/xml;", False)

    ThisWorkbook.Sheets(1).Cells(11, 1) = respText

    MsgBox respText
End Sub

d:\issues.xml content like below:

<?xml version="1.0" encoding="UTF-8"?>
<issue>
  <project_id>70711</project_id>
  <subject>Creating an issue with a uploaded file</subject>
  <uploads type="array">
    <upload>
      <token>80906.d90224c27d502787136ee83866dfc71e</token>
      <filename>128393.csv</filename>
      <description>128393.csv</description>
      <content_type>image/png</content_type>
    </upload>
  </uploads>
</issue>
</xml>