Forked from achudars/web-snippet-055 ( upload to Imgur in JavaScript)
Created
June 14, 2017 06:14
-
-
Save honktang/2e25b177fe30134bec9e1706425e3765 to your computer and use it in GitHub Desktop.
Use JavaScript to upload anonymously to Imgur using Imgur API and show the link to the file.
Make sure your API key is valid and working!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function upload(file) { | |
var imageLink =""; | |
/* Is the file an image? */ | |
if (!file || !file.type.match(/image.*/)) return; | |
var fd = new FormData(); | |
fd.append("image", file); // Append the file | |
fd.append("key", "<Imgur API key>"); | |
var xhr = new XMLHttpRequest(); | |
xhr.open("POST", "http://api.imgur.com/2/upload.json"); | |
xhr.onload = function() { | |
var link = JSON.parse(xhr.responseText).upload.links.imgur_page; | |
document.querySelector("#link").href = link; | |
document.querySelector("#link").innerHTML = link; | |
var imageLink = ""+document.querySelector("#link").innerHTML.replace("http://imgur.com/", "http://i.imgur.com/")+".jpg"; | |
/* Image Preview */ | |
document.getElementById("result").style.display = "inline"; | |
document.getElementById("link-to-image").style.background = "url(" + imageLink + ") center center no-repeat"; | |
}; | |
/* Send the formdata */ | |
xhr.send(fd); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Slightly longer version, which uses clipboard interaction to upload to imgur v3 API https://gist.github.com/Lewiscowles1986/6cac3472336a1cf009a88bde56a65fe3