'Trying to upload a picture via an API but get "Empty upload source" error
I'm a beginner with APIs. I'm trying to upload a file to imgBB using an API. But I get the error message: "{"status_code":400,"error":{"message":"Empty upload source.","code":130},"status_txt":"Bad Request"}" Anyone knows why?
Sub EncodeFile()
Dim strPicPath As String
Dim TestFile As String
strPicPath = "X:\xxxxxxx\xxxxx.png"
Const adTypeBinary = 1 ' Binary file is encoded
' Variables for encoding
Dim objXML
Dim objDocElem
' Variable for reading binary picture
Dim objStream
' Open data stream from picture
Set objStream = CreateObject("ADODB.Stream")
objStream.Type = adTypeBinary
objStream.Open
objStream.LoadFromFile (strPicPath)
' Create XML Document object and root node
' that will contain the data
Set objXML = CreateObject("MSXml2.DOMDocument")
Set objDocElem = objXML.createElement("Base64Data")
objDocElem.DataType = "bin.base64"
' Set binary value
objDocElem.nodeTypedValue = objStream.Read()
' Get base64 value
TestFile = objDocElem.Text
With CreateObject("MSXML2.ServerXMLHTTP")
.Open "POST", "https://api.imgbb.com/1/upload?key=xxxxxxxxxxxxxxxxxxxxxxxx"
.setRequestHeader "Content-type", "application/json"
.send TestFile
MsgBox (.ResponseText)
End With
End Sub
Solution 1:[1]
As @Toddleson notes, the content of the POST should be the base64 of the file, assigned to a parameter "image". You can see that in the CURL example on the API page:
"image=R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
I would factor out the Base64 functionality into a re-usable function:
Sub EncodeFile()
Dim strPicPath As String
strPicPath = "X:\xxxxxxx\xxxxx.png"
With CreateObject("MSXML2.ServerXMLHTTP")
.Open "POST", "https://api.imgbb.com/1/upload?key=xxxxxxxxxxxxxxxxxxxxxxxx"
'.setRequestHeader "Content-type", "application/json" 'not sending json...
.send "image=" & FileToBase64(strPicPath)
MsgBox .ResponseText
End With
End Sub
'return the contents of a file as Base64
Function FileToBase64(fPath As String) As String
Const adTypeBinary = 1 ' Binary file is encoded
Dim objStream As Object, objXML As Object, objDocElem As Object
Set objStream = CreateObject("ADODB.Stream")
objStream.Type = adTypeBinary
objStream.Open
objStream.LoadFromFile fPath
Set objXML = CreateObject("MSXml2.DOMDocument")
Set objDocElem = objXML.createElement("Base64Data")
objDocElem.DataType = "bin.base64"
objDocElem.nodeTypedValue = objStream.Read()
objStream.Close
FileToBase64 = objDocElem.Text
End Function
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tim Williams |