0

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!

candlejack
  • 1,189
  • 2
  • 22
  • 51
  • 3
    Do you have to figure it out from the client side? Couldn't the server figure that out for you? – Mike Cluck Apr 11 '17 at 17:02
  • can't you populate extension in your json? – Tushar Gupta Apr 11 '17 at 17:04
  • Possible duplicate of [How do I check if file exists in jQuery or JavaScript?](http://stackoverflow.com/questions/3646914/how-do-i-check-if-file-exists-in-jquery-or-javascript) – Dshiz Apr 11 '17 at 17:12
  • @MikeC Interesting, maybe I can send it from the webservice. – candlejack Apr 11 '17 at 17:40
  • @Dshiz it is not the same, "checking" is the process that I need to repeat, I need to guess, so check multiple time until find out the right extension. – candlejack Apr 11 '17 at 17:44
  • @MikeC Your comment was the answer, please put it as an answer so I can mark this as Solved. Thanks! – candlejack Apr 11 '17 at 17:48
  • @alessadro Because your question is specific to client-side, I provided a client-side answer. Perhaps you could update your question if you require a server-side answer. – Dshiz Apr 11 '17 at 18:40

1 Answers1

1

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;
}
Dshiz
  • 3,099
  • 3
  • 26
  • 53