candlejack
candlejack

Reputation: 1209

How to guess file extension with JavaScript (client side)

I have a tiny webapp, I have multiple folders in it (each folder name is an ID), in each folder there are an image that can be JPG, PNG or GIF

The structure is this:

$("#logo").attr('src','../images/article/'+json.id+'/logo.jpg');

I don't know the real extension of the file, many articles have JPG, other have PNG and some others have GIF extension, that's all the possibilities.

How can I guess and set the right extension, maybe using a sort of onerror event?

Thanks for reading, and please forgive my bad english!

Upvotes: 0

Views: 81

Answers (1)

Dshiz
Dshiz

Reputation: 3341

You can use the jquery .each() function with a check of whether or not the file exists like below. If you need to pass the json.id through you would need to nest this in a for loop. Note: I have not tested this code.

var url;
$.each([ 'gif', 'jpg', 'png' ], function( index, value ) {
  url='../images/article/'+json.id+'/logo.' + value);
  if(UrlExists(url)){
    $("#logo").attr('src',url);
  } else {
    //handle false
  }
});

function UrlExists(url)
{
  var http = new XMLHttpRequest();
  http.open('HEAD', url, false);
  http.send();
  return http.status!=404;
}

Upvotes: 1

Related Questions