[Javascript] Image detection
Andrew Clover
and-babble at doxdesk.com
Thu Apr 7 11:42:19 CDT 2005
Roland Neilands <rneilands at pulsemining.com.au> wrote:
> Does anyone know of a simple way of detecting in Javascript
> if a given file is an image or not?
Try setting the src of an <img> to point to the file in question. If you
get an onload event, it was an image in a format the browser recognises.
If you get an onerror event, it wasn't (or the resource was unfetchable).
> Is checking a list of files extensions the only way?
Pedantically speaking, it isn't a way at all - a URI's file extension
may not have anything to do with the type of the resource it returns. A
common example is a .cgi script, which could spit out a file with any
MIME type. I don't know if there are cases like this in your intranet
though.
If you *do* go for guessing-from-extension, a regexp might not be the
clearest solution. The shortest solution, perhaps, but traditionally not
necessarily the most correct. For example the version you posted:
> new RegExp("jpg|gif|bmp|tif","i");
would match anywhere in the string, so 'stiff_gift.exe' would be
considered an image. One way to do it without regexps might be:
var path= uri.split('?', 1)[0]; // remove any query string
var parts= path.split('.');
var ext= path[path.length-1]; // get the last .xxx part
var isim= ext=='jpg'||ext=='jpeg'||ext=='gif'||ext=='png'||ext=='bmp';
If you want TIFF in there too you should probably test for .tiff as well
as .tif, but typically web browsers won't display this format anyway.
--
Andrew Clover
mailto:and at doxdesk.com
http://www.doxdesk.com/
More information about the Javascript
mailing list