Steps to upload an image using an API

I am attempting to use an API to upload a file to imgBB, but I encountered the following error message:

{"status_code":400,"error":{"message":"Empty upload source.","code":130},"status_txt":"Bad Request"}

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

Answer №1

It has been pointed out by @Toddleson that the content of the POST request should consist of the base64 representation of the file, assigned to a parameter called "image". This can be observed in the CURL example provided on the API page:

"image=R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"

To enhance reusability, it is recommended to extract the Base64 conversion functionality into a separate 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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Efficient Local Database with Javascript

When storing a substantial amount of data, such as a big hashmap in JavaScript, what would be the optimal format for quick retrieval while also supporting Unicode? Would XML or JSON be better suited for this purpose? ...

Java is a powerful programming language that allows developers to generate personalized JSON strings by utilizing instantiated

There exists a defined class as shown below: @Data // lombok public class MyData { @Required // my custom annotation String testValue1; Integer testValue2; } An instance of myData is created like this: MyData myData = new MyData(); myData.setT ...

pyOWM is failing to yield the desired outcome

After obtaining my API key, I attempted to integrate the code snippet below: import pyowm owm = pyowm.OWM('API key') mgr = owm.weather_manager() Forecast = mgr.forecast_at_place('London', '3h').forecast max_temperature=[] min ...

Issues with decoding JSON data in PHP

Struggling to assign a JSON Object to a PHP Variable? When attempting to use var_dump, it's showing NULL. Here is the PHP code: <?php $json = utf8_encode(file_get_contents('http://socialclub.rockstargames.com/ajax/stat/1/profile_body/sta1/ ...

The error message "ch.match is not a function" appeared in the Javascript code

Here are two functions that I need help with: //Function A var ltrToNato = function(ch) { var x = ch; var nato = ('{"A": "Alpha", "B": "Bravo", "C": "Charlie", "D": "Delta", "E": "Echo", "F": "Foxtrot", "G": "Golf", "H": "Hotel", "I": "India" ...

Error encountered while attempting to make AJAX call: "`$.ajax` parse error on JSON object: {"vErrorsFound":true,"vMessage"

I am trying to update my code from using jQuery 1.3.2 to jQuery 1.5, but I am facing issues with parsing JSON data. I have a PHP script that returns the following JSON object using json_encode: {"vErrorsFound":true,"vMessage":"Login Failed"} I have exper ...

Sending JSON data with Python and fetching the response

I've been working on a Python script to make a post request, but I'm not receiving any response. Everything seems correct in my code, so I suspect there might be an issue with the service itself causing the lack of response. Can anyone spot if th ...

What is the process through which IPCRenderer.send() converts data into JSON serialization?

When attempting to transmit details about an error event using ipcRenderer.send("error", errorObject), I noticed that my Error object ends up being serialized as '{}' in the listener. It is common knowledge that ipcRenderer internally serializes ...

Conducting an AngularJS AJAX call within a Symfony2 environment and utilizing Doctrine to generate a JSON

Currently, I am working on a project involving Symfony2, Doctrine, and AngularJS. While Symfony2 and Doctrine are not causing any issues, I am facing difficulties when using an ajax request with AngularJS. The problem lies in either the data not loading pr ...

Unable to observe modifications in json file within java project (jsp)

I am currently using IntelliJ IDEA to develop a web project with JSP. I retrieve data from a file called "customer.json", and when I click on a button, I update this file in the backend. However, after trying to fetch the updated data again, it still reads ...

What could be causing the HTTP response Array length in Angular to be undefined?

Currently, I am facing an issue while retrieving lobby data from a Spring Boot API to display it in my Angular frontend. After fetching the data and mapping it into an object array, I encountered a problem where the length of the array turned out to be und ...

The WCF response from the Ajax call reported that the incoming message had an unexpected format of 'Raw'. The operation was expecting different message formats

Help needed with .NET framework 3.5. I'm facing an issue with my Get WCF services, even though they seem to be working fine using the same method. Can't pinpoint what's causing the problem. WCF: [OperationContract] [WebInvoke(Metho ...

Creating an object in AngularJS by merging data from three separate API calls

I am looking to develop a Jenkins dashboard using AngularJS. I am considering combining data from three different API calls to create an object that can be used in the HTML file with ng-repeat, but I'm not sure if this is the best approach. The desir ...

Mastering the Art of Accelerating getJSON Array Data

Currently, I am facing a challenge with retrieving a large array (4MB) of data from the server side. I have been utilizing the jQuery getJSON method to obtain the array data and display it on the browser. However, this process has proven to be quite slow ...

What is the best way to display text from a file on a different html page using jQuery's json2html?

Here is the json data: var data = [ { "name": "wiredep", "version": "4.0.0", "link": "https://github.com/taptapship/wiredep", "lice ...

Creating a 2-dimensional array from a JSON using the MINIJson library

I'm new to JSON and also a bit inexperienced with c#. However, I have a task of loading JSON data and setting up a gamegrid in unity3d based on a 2d array from the JSON file. I have been using MINIJson from Darktable and I can fetch simple data succe ...

From Panda's Den to JSON Empire: Unraveling the Dataframe

After an exhaustive review and attempt at implementing all the other solutions on SO related to this challenge, I have yet to find a working solution. Question: How can I convert employee and supervisor pairs into a dynamic hierarchical JSON structure for ...

Grails - JSONBuilder - Specification for toPrettyString() results in a stack overflow exception

I need to create a unit test that returns JSON data. To achieve this, I am utilizing the toPrettyString() method from JSONBuilder. Here is the class under consideration: class Lugar { String sigla String nombre Coordenada coordenada String t ...

NextJS - Error: Invalid JSON format, starting with a "<" symbol at position 0

After following a tutorial on NextJS, I attempted to make some modifications. My goal was to include the data.json file on the page. However, I kept encountering the error message "Unexpected token < in JSON at position 0." I understand that I need to con ...

Preparing my JSON data for visualization on a chart

I have successfully retrieved data using this API, but now I need to transform it into a chart within my react project. As a newcomer to JS and React, I am struggling to create a chart with the JSON data. My objective is to display prices by bedrooms over ...