Skip to content

Instantly share code, notes, and snippets.

@Harry260
Created January 1, 2022 12:10
Show Gist options
  • Select an option

  • Save Harry260/074f90d59bec3caa42186dde0ad8612c to your computer and use it in GitHub Desktop.

Select an option

Save Harry260/074f90d59bec3caa42186dde0ad8612c to your computer and use it in GitHub Desktop.
Upload Image to Imgur.com with Javascript - Javascript wrapper for Imgur

Imgur Wrapper for JS

This is a Wrapper for Imgur to upload images easily!

Usage

  • Firstly, Get a Client Id from Imgur Check this out
  • Create an Input element with type="file" attribute and any selector, eg. id: #imgur
<input type="file" id="imgur">
  • Use the Class Imgur(<client-id>, <input-selector>, <callback)>) with the parameters
Parameter Description Example Required
Client ID Your Imgur API Client ID "79b8XXXXXXXXff6" YES
Input Selector The css selector of your input element "#input" YES
Callback Callback Function which has the Link and other data of the image console.log NO

Example Usage

...

<body>
  <input type="file" id="#imgur">
  <script src="/path/to/script/script.js"></script>
  <script>
    new Imgur("79b89d2f1266ff6", "#imgur", console.log)
  </script>
</body>

...
class Imgur {
constructor(clientId, InputElement, callback) {
(clientId.includes("Client-ID")) ? this.clientId = clientId : this.clientId = "Client-ID " + clientId
this.InputElement = InputElement;
const file = document.querySelector(this.InputElement);
file.addEventListener("change", ev=>{
const formData = new FormData()
formData.append("image", ev.target.files[0])
fetch("https://api.imgur.com/3/image/", {
method: "post",
headers:{
Authorization: this.clientId
},
body:formData
}).then(data => data.json()).then(data => {
if(typeof callback === "function"){
callback(data.data)
}
})
.catch(err => console.err(err))
})
}
}
class Imgur{constructor(t,e,n){t.includes("Client-ID")?this.clientId=t:this.clientId="Client-ID "+t,this.InputElement=e;document.querySelector(this.InputElement).addEventListener("change",(t=>{const e=new FormData;e.append("image",t.target.files[0]),fetch("https://api.imgur.com/3/image/",{method:"post",headers:{Authorization:this.clientId},body:e}).then((t=>t.json())).then((t=>{"function"==typeof n&&n(t.data)})).catch((t=>console.err(t)))}))}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment