EDIT Changing the title so that it might be helpful to others

I am trying to upload an image to imgbb using their api using Axios, but keep getting an error response Empty upload source.

The API docs for imgbb shows the following example:

curl --location --request POST "https://api.imgbb.com/1/upload?key=YOUR_CLIENT_API_KEY" --form "image=R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"

My node code to replicate this is:

    const fs = require('fs')
const FormData = require('form-data')
const Axios = require('axios').default

let file = '/tmp/the-test.png'
let url = 'https://api.imgbb.com/1/upload?key=myapikey'
var bodyData = new FormData();
let b = fs.readFileSync(file, {encoding: 'base64'})
bodyData.append('image', b)
  method: 'post',
  url: 'url',
  headers: {'Content-Type': 'multipart/form-data' },
  data: {
    image: bodyData
}).then((resolve) => {
}).catch(error => console.log(error.response.data));

But I keep getting the following error response..

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

Not sure exactly where I am failing.

For the sake of completion and for others, how does the --location flag translate to an axios request?

1 Answers

securisec On Best Solutions

The issue was in the headers. When using form-data, you have to make sure to pass the headers generated by it to Axios. Answer was found here

headers: bodyData.getHeaders()

Working code is:

const fs = require('fs');
const FormData = require('form-data');
const Axios = require('axios').default;

let file = '/tmp/the-test.png';
var bodyData = new FormData();
let b = fs.readFileSync(file, { encoding: 'base64' });
bodyData.append('image', b);
  method  : 'post',
  url     : 'https://api.imgbb.com/1/upload?key=myapikey',
  headers : bodyData.getHeaders(),
  data    : bodyData
  .then((resolve) => {
  .catch((error) => console.log(error.response.data));