Sarmad Gardezi

Sarmad Gardezi

a freelance developer


Home about Portfolio Blog

Image Uploader with Imgur API and JavaScript

If you are building a file uploader app that would allow users to upload images from the local disk to the web, Imgur is a good platform to start with. FileStack, Cloudinary and UploadCare are some popular web services that offer simple file upload widgets but the Imgur API is free for non-commercial usage or if your app is open source.

Go to api.imgur.com, register your application and generate the client ID. All HTTP requests for uploading images to Imgur must include the client_id in the authorization header and this would also let you upload images anonymously without the image being tied to your personal Imgur account.

<form id="imgur">
<input type="file" class="imgur" accept="image/*" data-max-size="5000"/>
</form>

In the HTML section of your website, include an <input> field of type file and set the accept attribute to “image/*” so that file selector window would only allow selection of image files. We’ll also add a data attribute (max-size) to reject files that are bigger than a specific size (in Kb).

Next, we use jQuery to attach an onChange event handler to the input field that gets triggered when the user clicks the input field and selects a file.


$("document").ready(function() {

$('input[type=file]').on("change", function() {

var $files = $(this).get(0).files;

if ($files.length) {

// Reject big files
if ($files[0].size > $(this).data("max-size") * 1024) {
console.log("Please select a smaller file");
return false;
}

// Begin file upload
console.log("Uploading file to Imgur..");

// Replace ctrlq with your own API key
var apiUrl = 'https://api.imgur.com/3/image';
var apiKey = 'ctrlq';

var settings = {
async: false,
crossDomain: true,
processData: false,
contentType: false,
type: 'POST',
url: apiUrl,
headers: {
Authorization: 'Client-ID ' + apiKey,
Accept: 'application/json'
},
mimeType: 'multipart/form-data'
};

var formData = new FormData();
formData.append("image", $files[0]);
settings.data = formData;

// Response contains stringified JSON
// Image URL available at response.data.link
$.ajax(settings).done(function(response) {
console.log(response);
});

}
});
});

The onChange handler makes as synchronous AJAX file upload request to the Imgur API with the image file sent inside the FormData object.

The form’s encoding type is set to multipart/form-data and thus the sent data is in the same format as the form’s submit method.

After the image is upload, Imgur returns a JSON response containing the public URL of the uploaded image and the deletehash that can be used to delete the file from the Imgur servers.



RELATED POSTS

Video Tutorials