Descargar archivo en Flex usando la clase FileReference
September 12th, 2009Bueno una de las preguntas mas frecuentes en las aplicaciones RIA's es si ¿se pueden descargar archivos atravez de ellas? y la respuesta a esa pregunta es sip! si se puede,
Veamos un ejemplo de como descargar archivos con flex.
Vamos a descargar el archivo Zip que contiene el codigo fuente de este ejemplo.
-
<?xml version="1.0" encoding="utf-8"?>
-
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
-
layout="vertical"
-
verticalAlign="middle"
-
backgroundColor="white"
-
creationComplete="init();" viewSourceURL="srcview/index.html">
-
-
<mx:Script>
-
<![CDATA[
-
import mx.controls.Alert;
-
import mx.collections.ArrayCollection;
-
import flash.net.FileReference;
-
-
[Bindable]
-
[Embed('assets/disk.png')]
-
private var diskIcon:Class;
-
-
[Bindable]
-
private var arrColl:ArrayCollection;
-
-
/* URL del archivo que vamos a descargar. */
-
private const FILE_URL:String = "http://zonadevelop.netau.net/wp-content/examples/post_52/srcview/DescargarArchivo_Flex.zip";
-
-
private var fileRef:FileReference;
-
private var urlReq:URLRequest;
-
-
private function init():void {
-
/* Inicializamos en ArrayCollection que guardara los eventos */
-
arrColl = new ArrayCollection();
-
-
/* Creando la referencia al archivo de la url en la variable FILE_URL */
-
urlReq = new URLRequest(FILE_URL);
-
-
fileRef = new FileReference();
-
fileRef.addEventListener(Event.CANCEL, doEvent);
-
fileRef.addEventListener(Event.COMPLETE, doEvent);
-
fileRef.addEventListener(Event.OPEN, doEvent);
-
fileRef.addEventListener(Event.SELECT, doEvent);
-
fileRef.addEventListener(HTTPStatusEvent.HTTP_STATUS, doEvent);
-
fileRef.addEventListener(IOErrorEvent.IO_ERROR, doEvent);
-
fileRef.addEventListener(ProgressEvent.PROGRESS, doEvent);
-
fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doEvent);
-
}
-
-
private function doEvent(evt:Event):void {
-
/* Creamos un referencia al objeto FileReference */
-
var fr:FileReference = evt.currentTarget as FileReference;
-
-
/* Agregamos los eventos al arreglo y luego a la grilla en orden del tipo de evento */
-
arrColl.addItem({data:arrColl.length+1, type:evt.type, eventString:evt.toString()});
-
-
try {
-
/* Actualizamos en Modelo. */
-
fileRefModel.creationDate = fr.creationDate;
-
fileRefModel.creator = fr.creator;
-
fileRefModel.modificationDate = fr.modificationDate;
-
fileRefModel.name = fr.name;
-
fileRefModel.size = fr.size;
-
fileRefModel.type = fr.type;
-
/* Mostrando el TextControl. */
-
txt.visible = true;
-
} catch (err:*) {
-
/* ... */
-
}
-
}
-
-
private function downloadSourceCodeZip():void {
-
/* Borramos el contenido del array collection. */
-
arrColl = new ArrayCollection();
-
/* Ocultamos el Text control. */
-
txt.visible = false;
-
/* Empezamos la descarga. */
-
fileRef.download(urlReq);
-
}
-
-
private function showAlert(item:Object):void {
-
Alert.show(item.eventString, item.type);
-
}
-
]]>
-
</mx:Script>
-
-
<!-- Creamos el modelo para los datos de los eventos -->
-
<mx:Model id="fileRefModel">
-
<file>
-
<creationDate>{""}</creationDate>
-
<creator>{""}</creator>
-
<modificationDate>{""}</modificationDate>
-
<name>{""}</name>
-
<size>{""}</size>
-
<type>{""}</type>
-
</file>
-
</mx:Model>
-
-
<!-- Boton para descargar el archivo -->
-
<mx:Button id="downloadBtn" label="Descarga el codigo fuente aqui!" icon="{ this.diskIcon }" click="downloadSourceCodeZip()" toolTip="{FILE_URL}" height="40" />
-
-
<!-- Grilla que musra los eventos -->
-
<mx:DataGrid id="debug" dataProvider="{arrColl}" width="{downloadBtn.width}" rowCount="5" rowHeight="22" itemClick="showAlert(event.currentTarget.selectedItem)">
-
<mx:columns>
-
<mx:DataGridColumn dataField="data" headerText="#" width="20" />
-
<mx:DataGridColumn dataField="type" headerText="Type" showDataTips="true" dataTipField="eventString" />
-
</mx:columns>
-
</mx:DataGrid>
-
-
<mx:Text id="txt" condenseWhite="true" visible="false">
-
<mx:text>
-
creationDate: {fileRefModel.creationDate}
-
creator: {fileRefModel.creator}
-
modificationDate: {fileRefModel.modificationDate}
-
name: {fileRefModel.name}
-
size: {fileRefModel.size}
-
type: {fileRefModel.type}
-
</mx:text>
-
</mx:Text>
-
-
</mx:Application>
Luego de revisar el codigo nos quedaria algo asi:
