Upload file to file.io using POST method

前端 未结 1 546
日久生厌
日久生厌 2021-01-15 03:43

I have found a link at SO that may make difference at this query Upload a Picture to file.io (HTTP Post) in VBA The code from this link

相关标签:
1条回答
  • 2021-01-15 04:04

    It looks to me like the final boundary is in the wrong place ie before the file content. Try

    Sub UploadToIO()
    
        Const PATH = "c:\tmp\"
        Const FILENAME = "testimage.png"
        Const CONTENT = "image/png"
        Const URL = "https://file.io"
    
        ' generate boundary
        Dim BOUNDARY, s As String, n As Integer
        For n = 1 To 16: s = s & Chr(65 + Int(Rnd * 25)): Next
        BOUNDARY = s & CDbl(Now)
    
        Dim part As String, ado As Object
        part = "--" & BOUNDARY & vbCrLf
        part = part & "Content-Disposition: form-data; name=""file""; filename=""" & FILENAME & """" & vbCrLf
        part = part & "Content-Type: " & CONTENT & vbCrLf & vbCrLf
    
        ' read file into image
        Dim image
        Set ado = CreateObject("ADODB.Stream")
        ado.Type = 1 'binary
        ado.Open
        ado.LoadFromFile PATH & FILENAME
        ado.Position = 0
        image = ado.read
        ado.Close
    
        ' combine part, image , end
        ado.Open
        ado.Position = 0
        ado.Type = 1 ' binary
        ado.Write ToBytes(part)
        ado.Write image
        ado.Write ToBytes(vbCrLf & "--" & BOUNDARY & "---")
        ado.Position = 0
        'ado.savetofile "c:\tmp\debug.bin", 2 ' overwrite
    
        ' send request
        With CreateObject("MSXML2.ServerXMLHTTP")
            .Open "POST", URL, False
            .setRequestHeader "Content-Type", "multipart/form-data; boundary=" & BOUNDARY
            .send ado.read
            Debug.Print .responseText
        End With
    
        MsgBox "File: " & PATH & FILENAME & vbCrLf & _
               "Boundary: " & BOUNDARY, vbInformation, "Uploaded to " & URL
    
    End Sub
    
    Function ToBytes(str As String) As Variant
    
        Dim ado As Object
        Set ado = CreateObject("ADODB.Stream")
        ado.Open
        ado.Type = 2 ' text
        ado.Charset = "_autodetect"
        ado.WriteText str
        ado.Position = 0
        ado.Type = 1
        ToBytes = ado.read
        ado.Close
    
    End Function
    
    
    0 讨论(0)
提交回复
热议问题