During my early days of programming in flex i got a lot confused with the uplaod/download feature of flex, which in normal HTML and others are pretty easy. A sample upload file code in HTML would look like this:
< action="random.php" method="post" enctype="multipart/form-data">
Please choose a file: < type="file" name="uploaded">
<input type="submit" value="Upload" >
which is hardly 3 lines of code.. but in flex we have much more formalities to be fullfilled before u can upload any file to the server...but you can use the same php/cf or any other server code for recieving the file uploaded...coz the flex is actually html+javascript and the effects done in flash.
Well...back to the topic.. For uploading a file in flex u need to import the "flash.net.*" class and flash.events class for the upload and other response events.The code goes like this:
<mx:Script>
<!--[CDATA[
import flash.events.*;
import flash.net.FileReference;
import flash.net.URLRequest;
import mx.controls.*;
import mx.controls.ProgressBar;
import mx.core.UIComponent;
//URL of the remote upload script or the server script which recieves the file.
private const UPLOAD_URL:String = "http://www.your-url.com/php_file_location";
/*var for accessing files ,you can also use FileReferenceList for multiple file upload scenario*/
private var fr:FileReference;
/* function that alows user to select a file through browse and each event listerts calls the respective function */
private function startUpload():void
{
fr = new FileReference();
fr.browse();
fr.addEventListener(Event.SELECT, selectHandler);
fr.addEventListener(Event.OPEN, openHandler);
fr.addEventListener(Event.COMPLETE, completeHandler);
}
/*Begin uploading the file specified in the UPLOAD_URL constant.*/
private function selectHandler(event:Event):void
{
textip1.text=event.target.name;
var request:URLRequest = new URLRequest();
request.url = UPLOAD_URL; fr.upload(request);
}
/*while the file is opened for upload you can add event here to alert file name or activate or disable any buttons etc...*/
private function openHandler(event:Event):void
{ /* any code snippet to show uploading */ }
/*event called once the upload has completed.*/
private function completeHandler(event:Event):void
{
Alert.show("UPLOADING COMPLETE");
cancel.enabled = false;
}
/*cancel the upload in progress and disable the cancel button.*/
public function cancelUpload():void
{
fr.cancel();
Alert.show( "UPLOAD CANCELLED");
cancel.enabled = false;
}
]]-->
The download file code is pretty much the same where instead of fr.upload();
you just need to type fr.download("filename.extension")
and the URL will be the filelocation.
Can this be used to read an xml file from a server, alter it and send it back?
ReplyDeleteHow would you upload a "file" that has been created in flex? For example, you read an xml document, modify it, and then want to upload it back to the server? Not a file on disk, and not a file from a database?
ReplyDelete