ActionScript 2 – Find File Extension
Let’s say we have a scenario where we have an XML file that contains references to files that are mixed media types and our Flash file will conduct a certain operation based on the file’s extension. You could structure your XML like this:
<asset url="movie.flv" type="movie" /> <asset url="image.jpg" type="image" />
But type=”movie” isn’t quite so user-friendly and has the possibility for mistakes. What would be better is this:
<asset url="movie.flv" /> <asset url="image.jpg" />
We are going to have a little ActionScript to find out what the file extension is.
*edit* – New code recommended by Luiz Fernando – Thanks! Your’s works much better!
var file:String = "movie.flv"; var fileExtension:String = file.substr(file.lastIndexOf('.')+1, file.length-file.lastIndexOf('.')); trace(fileExtension); // output --- flv
From here you’d want to run some checks for the file types you wish to support and run some code to showcase different types of media content.
loadAsset(file, fileExtension); function loadAsset(asset, fileType) { var cleanFileType:String = fileType.toLowerCase(); switch(cleanFileType) { case "jpg" : case "png" : case "jpeg" : case "gif" : // load image; (asset) break; case "swf" : // load swf; (asset) break; case "flv" : case "f4v" : case "mp4" : // load video (asset) break; } }

Or you can seek for the last dot, where anything beyond is the extension:
var myvar:String = “movie.flv”;
var fileExtension:String = myvar.substr(myvar.lastIndexOf(‘.’)+1, myvar.length-myvar.lastIndexOf(‘.’));
trace(fileExtension);
this works with all extension sizes :]
Comment by Luiz Fernando — April 21, 2009 @ 12:42 pm
Thanks Luiz!
Yours is a lot better.
Comment by admin — April 21, 2009 @ 1:09 pm
you have a typo in your code:
var fileExtension:String = myvar.substr(file.lastIndexOf(‘.’)+1, file.length-
should be:
var fileExtension:String = file.substr(file.lastIndexOf(‘.’)+1, file.length-
see the “myvar” -> “file”
thanks anyway, works perfect!
Comment by ame — October 1, 2009 @ 11:00 am
You’re right, thanks.
Comment by admin — October 1, 2009 @ 11:04 am