February 26, 2009

ActionScript 2 – Find File Extension

Filed under: Flash, Freebies — Tags: , , — admin @ 10:25 pm

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;
	}
}

© 2010 Aaron Benson. All rights reserved.

Powered by WordPress