How to upload an image to ImgBB API using Javascript in a firefox addon

扶醉桌前 提交于 2021-02-19 06:06:40

问题


Info on the API can be found here. It does not give any details for using with Javascript, only with curl.

Have tried numerous different methods from old posts on here but this is the closest I have got so far.

function main() {
    var ul = document.querySelector('.redactor_toolbar')

    if(ul != null)
    {
        var new_li = document.createElement('li')
        var new_a = document.createElement('a')
        new_li.appendChild(new_a)
        ul.appendChild(new_li)

        new_a.addEventListener('click', function() {
            var input = document.createElement('input');
            input.type = 'file';

            input.onchange = e => {
                uploadImage(e.target.files[0])
            }

            input.click();
        })
    }
 }

 async function uploadImage(img)
 {
    var form = new FormData();
    form.append('image', img)

    var url = 'https://api.imgbb.com/1/upload?key=8d5867a9512390fb5e5dc97839aa36f6' 

    const config = {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Connection': 'keep-alive',
            'Content-Type': 'application/json',
        },
        body: form
    }

    const response = await fetch(url, config)
    const json = await response.json()

    console.log(response)
 }

The JSON response:


回答1:


is the same problem for mi application.

Create

<input type="file" id="input_img" onchange="fileChange()" accept="image/*">

The code javascript

function fileChange(){
var file = document.getElementById('input_img');
var form = new FormData();
form.append("image", file.files[0])

var settings = {
  "url": "https://api.imgbb.com/1/upload?key=8d5867a9512390fb5e5dc97839aa36f6",
  "method": "POST",
  "timeout": 0,
  "processData": false,
  "mimeType": "multipart/form-data",
  "contentType": false,
  "data": form
};


$.ajax(settings).done(function (response) {
  console.log(response);
  var jx = JSON.parse(response);
  console.log(jx.data.url);


});

}

This work for me



来源:https://stackoverflow.com/questions/60809635/how-to-upload-an-image-to-imgbb-api-using-javascript-in-a-firefox-addon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!