May 10, 2007

AS3 Tip of the Day

Its that time again. Today we will be discussing the download method of the FileReference class. Unlike other methods that require a URLRequest, this one requires that request to be the complete path to the file on the server and not a relative one. While this is a pain, it is possible. Here is a download method that will do this for you:

private function _download($file:String, $i:Int=0):void{ //$i is how many directories you would like to traverse
  var path:String = loaderInfo.url;//Full path to file
  while($i>=0){
    path = path.slice(0, path.lastIndexOf("/"));
    $i--;
  }
  path += "/";//Add the trailing slash back
  _request.url = path+$file;
  try{
    _file.download(_request);//Get that file
  }catch($e:Error){
    //Do some error handling
  }
}

Note: This method should be inside a class that is a descendant of the DisplayObject in order for the property loaderInfo to be available.

This comes in handy for when you want to download files that have a MIME type that would normally open in the browser on default. However this simple method below works best for grabbing other files:

private function _download($file:String, $relative:String=""):void{
  _request.url = $relative+$file;
  navigateToURL(_request,"_self");
}


Whoa! 2 tips in 2 days. Hope I can keep up this momentum...

Share this Post


                           


Speak






Submit »