Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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!
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();"POST", "");
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("", "")+".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 */
Copy link

Lewiscowles1986 commented May 20, 2018

Is the upload always a jpg? You're checking for image mime-type, but then always assuming .jpg. It could be an Imgur nuance that they call files by the incorrect extension, but that is pushing back on client applications to be smarter than they are. I think you'd be better off retrieving the imgur_page as a separate resource, or regexing the file extension, or mapping from mime, then searching for the main image (it'll probably be marked up). Quite cool that it's this easy to send to Imgur though.

Edit: it returns a link to the upload in v3 (2 is now deprecated)

Copy link

Lewiscowles1986 commented May 20, 2018

Slightly longer version, which uses clipboard interaction to upload to imgur v3 API

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment