Clase Upload - ActionScript 3 | Phoxer.com
Clase Upload - ActionScript 3
03/02/2008

Muchas veces necesitamos manejar subidas de archivos en nuestros proyectos, esta clas las programé para ahorrar tiempo a la hora de manejar archivos.

La clase UploadFile la implementamos de esta manera:

import phoxer.Files.UploadFile;
 
var upl:UploadFile= new UploadFile();
 
//PHP service options
upl.fileTo="temp/FileManager.php";
upl.tipoArchivos="jpg,png,gif";
upl.fileName="nuevonombre";
upl.rutaFinal="ver";
 
//If the file is a image
upl.resizeImagen="200x200";
upl.resizeThums="50x50";
 
//aventos
upl.backSelect=function(file:FileReference):void{
    trace(file.name);
};
 
upl.backProgress=function(num:Number):void{
	trace("Uploading: "+num);
};
 
upl.backComplete=function(file:FileReference,fileName:String):void{
	trace(file.name+" Finished Uploaded");
};
 
upl.backError=function():void{
	trace("error");
};
 
upl.backCancel=function():void{
	trace("Cancel");
};

La clase Upload nesesita de un archivo PHP que maneja todo el paquete de información del lado del servidor, he escrito un ejemplo de como sería el servicio, pero basicamente funciona con cualquier servicio que utilicen.


/**
UploadManager v2.5
By .:{PHOXER}:.
http://www.phoxer.com
*/
 
$fileName=$_POST["fileName"];
$thumName="s".$fileName;
$createImage=$_POST["createImage"];
$createThums=$_POST["createThums"];
$imageW=$_POST["imgW"];
$imageH=$_POST["imgH"];
$thumW=$_POST["thumW"];
$thumH=$_POST["thumH"];
$root="../../";
if($_POST["rutaFinal"]!="null"){
	$rutaFinal=$root.$_POST["rutaFinal"];
	$rename=true;
}else{
	$rename=false;
}
//subir el archivo principal
$tempFolder="./";
$temporal = $tempFolder.$fileName;
$copiado=copy($_FILES["Filedata"]["tmp_name"], $temporal);
//TRABAJAR LAS IMAGENES
if($copiado){
	//RESIZE IMAGEN
	if($createImage=="true"){
		$basename = basename($temporal);
		$datos = getimagesize($temporal);
		if($datos[2]==1){$img = @imagecreatefromgif($temporal);} 
		if($datos[2]==2){$img = @imagecreatefromjpeg($temporal);} 
		if($datos[2]==3){$img = @imagecreatefrompng($temporal);} 
		$ratio = ($datos[0] / $imageW); 
		$altura = ($datos[1] / $ratio); 
		if($altura>$imageH){$imageW2=$imageH*$imageW/$altura;$altura=$imageH;$imageW=$imageW2;} 
		$thumb = imagecreatetruecolor($imageW,$altura); 
		imagecopyresampled($thumb, $img, 0, 0, 0, 0, $imageW, $altura, $datos[0], $datos[1]);
		if($datos[2]==1){imagegif($thumb,$tempFolder.$basename);} 
		if($datos[2]==2){imagejpeg($thumb,$tempFolder.$basename);} 
		if($datos[2]==3){imagepng($thumb,$tempFolder.$basename);} 
		imagedestroy($thumb);
		$fileName=$tempFolder.$basename;   
	}else{
		$fileName=$temporal;
	}
	//RESIZE THUMS
	if($createThums=="true"){
		$thumTemporal=$tempFolder.$thumName;
		$copythum=copy($fileName, $thumTemporal);
		if($copythum){
			$basename = basename($thumTemporal);
			$datos = getimagesize($thumTemporal);
			if($datos[2]==1){$img = @imagecreatefromgif($thumTemporal);} 
			if($datos[2]==2){$img = @imagecreatefromjpeg($thumTemporal);} 
			if($datos[2]==3){$img = @imagecreatefrompng($thumTemporal);} 
			$ratio = ($datos[0] / $thumW); 
			$altura = ($datos[1] / $ratio); 
			if($altura>$thumH){$thumW2=$thumH*$thumW/$altura;$altura=$thumH;$thumW=$thumW2;} 
			$thumb = imagecreatetruecolor($thumW,$altura); 
			imagecopyresampled($thumb, $img, 0, 0, 0, 0, $thumW, $altura, $datos[0], $datos[1]);
			if($datos[2]==1){imagegif($thumb,$tempFolder.$basename);} 
			if($datos[2]==2){imagejpeg($thumb,$tempFolder.$basename);} 
			if($datos[2]==3){imagepng($thumb,$tempFolder.$basename);} 
			imagedestroy($thumb);
			$thumName=$tempFolder.$thumName;
		}
	};
	//mover los archivos
	if($rename){
		$folder=$rutaFinal."/".basename($fileName);
		$mover=rename($fileName,$folder);
		if($createThums=="true"){
			$folder=$rutaFinal."/".basename($thumName);
			$mover=rename($thumName,$folder);
		}
	}
}
echo "checkFile=".$copiado;
echo "checkMove=".$mover;

acá esta la clase Upload:

/**
UploadManager By ::[PHOXER]::
http://www.phoxer.com
v 4.4;
*/
package phoxer.Files{
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.net.FileReferenceList;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.utils.Timer;
 
	import phoxer.Strings.UrlFileFormat;
	public class UploadFile{
		private var FileRef:FileReference;
		private var FileRefList:FileReferenceList;
		private var PostData:URLVariables;
		private var PostTo:URLRequest;
		//funciones		
		public var backSelect:Function=null;
		public var backProgress:Function=null;
		public var backCancel:Function=null;
		public var backOnUpload:Function=null;
		public var backComplete:Function=null;
		public var backError:Function=null;
		public var backFileListComplete:Function=null;
		//opciones extras
		public var fileTo:String;
		public var fileName:String="";
		public var rutaFinal:String;
		public var resizeImagen:String="";
		public var resizeThums:String="";
		private var timer:Timer = new Timer(6000, 1);
		public var tipoArchivos:String="*.*";
		private var createImage:Boolean=false;
		private var createThums:Boolean=false;
		private var imageSize:Array;
		private var thumSize:Array;
		private var isList:Boolean;
		private var listCount:int;
		private var filesToUpload:Array;
 
		public function selectFile():void{
			FileRef = new FileReference();
			isList=false;
			setUploadConfig();
			HandlersSelected(FileRef);
			FileRef.browse(getExtenciones(tipoArchivos));
		}
 
		public function selectFileList():void{
			FileRefList = new FileReferenceList();
			isList=true;
			setUploadConfig();
			HandlersSelected(FileRefList);
			FileRefList.browse(getExtenciones(tipoArchivos));
		}
 
		//Configuracion si es imagen
		private function setUploadConfig():void{
			if(resizeImagen!=""){
				imageSize= new Array();
				imageSize= resizeImagen.split("x");
				createImage=true;
			}else{
				createImage=false;
			}
			if(resizeThums!=""){
				thumSize= new Array();
				thumSize= resizeThums.split("x"); 
				createThums=true;
			}else{
				createThums=false;
			}
		}
 
		public function Upload():void{
			PostData = new URLVariables();
			PostData.fileName=getFileName();
			PostData.rutaFinal=rutaFinal;
			PostData.createImage=createImage;
			PostData.createThums=createThums;
			if(createImage){
				PostData.imgW=imageSize[0];
				PostData.imgH=imageSize[1];
			}
			if(createThums){
				PostData.thumW=thumSize[0];
				PostData.thumH=thumSize[1];
				PostData.thumName=String("s"+getFileName());
			}
			PostTo = new URLRequest(fileTo);
			PostTo.data = PostData;
			PostTo.method=URLRequestMethod.POST;
 
			if(backOnUpload!=null){
				backOnUpload();
			}
 
			FileRef.upload(PostTo);
			HandlersUpload(FileRef);
		}
 
		public function getFileName():String{
			var fln:String= (fileName=="")? UrlFileFormat.setUrlFile(FileRef.name):String(UrlFileFormat.setUrlFile(fileName)+FileRef.type)
			return fln;
		}
		public function getFileReference():FileReference{
			return FileRef;
		}
 
		public function cancelUpload():void {
			FileRef.cancel();
			if(backCancel!=null){
				backCancel();
			}
		}
 
		//eventos
		private function HandlersSelected(ev:IEventDispatcher):void {
			ev.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler,false,0,true);
            ev.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler,false,0,true);
            ev.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler,false,0,true);
            ev.addEventListener(Event.SELECT, EventSelected,false,0,true);
			if(backCancel!=null){
				ev.addEventListener(Event.CANCEL, EventCancelar,false,0,true);
			}
		}
		private function HandlersUpload(ev:IEventDispatcher):void {
			if(backError!=null){
				ev.addEventListener(IOErrorEvent.IO_ERROR, EventErrores,false,0,true);
			}
			if(backProgress!=null){
				ev.addEventListener(ProgressEvent.PROGRESS, EventProgress,false,0,true);
			}
			if(backComplete!=null){
				ev.addEventListener(Event.COMPLETE, EventComplete,false,0,true);
				ev.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,EventFinalComplete,false,0,true);
				timer.addEventListener(TimerEvent.TIMER, onTimerEnd,false,0,true);
			}
		}
		private function EventSelected(e:Event):void {
			if(isList){
				onFileListSelected();
			}
			if(backSelect!=null){
				backSelect(FileRef);
			}
		}
		private function EventCancelar(e:Event):void {
			backCancel();
		}
		private function EventErrores(e:IOErrorEvent):void {
			backError(String(e));
		}
 
		private function EventComplete(e:Event):void {
			timer.start();
			FileRef.removeEventListener(Event.COMPLETE, EventComplete);
		}
		private function onTimerEnd(e:TimerEvent):void{
			trace("EventTimerComplete")
			timer.stop();
			timer.removeEventListener(TimerEvent.TIMER, onTimerEnd);
			backComplete(FileRef,getFileName());
			FileRef.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA,EventFinalComplete);
		}
 
		private function EventFinalComplete(e:Event):void {
			trace("EventFinalComplete")
			timer.stop();
			timer.removeEventListener(TimerEvent.TIMER, onTimerEnd);
			backComplete(FileRef,getFileName());
			//FileList
			if(isList){
				checkFileListUpload();	
			}
		}
 
		private function httpStatusHandler(e:HTTPStatusEvent):void {
            trace("httpStatusHandler: " + e);
        }
        private function ioErrorHandler(e:IOErrorEvent):void {
            trace("ioErrorHandler: " + e);
            backError(String(e));
        }
		private function securityErrorHandler(e:SecurityErrorEvent):void {
            trace("securityErrorHandler: " + e);
            backError(String(e));
        }
 
		private function EventProgress(e:ProgressEvent):void {
			var total:Number = Math.round((e.bytesLoaded/e.bytesTotal)*100);
			backProgress(total);
			if(total==100){
				FileRef.removeEventListener(ProgressEvent.PROGRESS, EventProgress);
			}
		}
 
		//control de multiples archivos
		private function onFileListSelected():void{
			var fileList:Array = FileRefList.fileList;
			filesToUpload = new Array();
			listCount=0;
			for (var i:int=0;i<fileList.length;i++){
				var nm:String=(fileName=="")? fileList[i].name:String(getFileName()+i);
				filesToUpload.push({fr:fileList[i],fn:nm});
			}
			uploadNextFileInList();
		}
 
		private function uploadNextFileInList():void{
			FileRef = new FileReference();
			FileRef = filesToUpload[listCount].fr;
			HandlersSelected(FileRef);
			listCount++
		}
 
		private function checkFileListUpload():void{
			if(listCount!=filesToUpload.length){
				uploadNextFileInList();
				Upload();
			}else{
				if(backFileListComplete!=null){
					backFileListComplete();
				}
			}
		}
 
		public function getActualNumOfFilesUploaded():int{
			return listCount;
		}
		public function getTotalNumsOfFilesToUpload():int{
			return FileRefList.fileList.length;
		}
 
		//tipos de archivos
		private function getExtenciones(ext:String):Array {
			var extenciones:Array=ext.split(",");
			var exts:String="";
			var extIni:String="";
			var extFin:String="";
			for (var e:int=0; e<extenciones.length; e++) {
				exts=String("*."+extenciones[e]).toLowerCase();
				extIni+=exts;
				extFin+=exts;
				if (e<(extenciones.length-1)) {
					extIni+=",";
					extFin+=";";
				}
			}
			var filtros:FileFilter= new FileFilter(String("Files (" + extIni + ")"),extFin);
			return new Array(filtros);
		}
	}
}