PDA

View Full Version : How to test if a file exists?


RichardE
10-16-2002, 09:36 PM
How can I test to see if a thumbnail copy of a graphic file exists (thumbnail filename would start th_ ) ?

Thanks in advance!

beetle
10-16-2002, 09:40 PM
No way that I know of. Not with Javascript....

joh6nn
10-16-2002, 09:54 PM
sort of. images come with onerror events, which fire if there's a problem when the browser tries to load the picture. one such problem, would be the non existence of the image. it's not the only reason the image might error out though, so it's not perfect. but, maybe 90% of the time, it's going to be that the image doesn't exist, so you can go ahead and use it without worrying. here's an example:

var thumb = new Image();
thumb.onerror = function() {
alert('picture doesn't exist');
}
thumb.src = 'picture.gif';

note that you have to define the onerror event handler before you assign the source of the picture. if you assign the source first, then the picture could finish loading ( and finish erroring ) before the event handler is defined, and so it would never go off, even if there was a problem.