In this post I’ll show how to load a file with a file chooser dialog from your local HD into an Internet Flash application in your browser. In another post I’ve explained how to save a file to HD from Flash.
With a little workaround it is possible to load files into Flash in a way that it feels just as if you would do it with a common application: You are being asked with a standard system file dialog, which file you want to load in your application.
However, at first you have to park (i.e. upload) your file on a server in order to make it “publicly” available for your Flash app:
But step by step. The procedure goes like this:
- You open up a file browser in Flash.
- The user chooses a file from your HD and clicks OK.
- The file is being uploaded from your HD to the server.
- Flash loads the file from the server in itself.
This code should do all the file handling in Flash for you:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | private var fileRef:FileReference; private const FILE_UPLOAD_URL:String = "http://your-server.com/path/to/upload/flashUpload.php"; private const UPLOADED_XML_URL:String = "http://your-server.com/path/to/upload/"; private function initializeFileRef():void{ //FileReference allows you to open up system file chooser dialogs and //to simply upload files on a webserver fileRef = new FileReference(); //after a file has been chosen in the file chooser dialog the function //fileSelected will be called. fileRef.addEventListener(Event.SELECT, fileSelected); //after the chosen file has been uploaded to the server the function //uploadCompleted will be called fileRef.addEventListener(Event.COMPLETE, uploadCompleted); } /** * upload chosen file from file chooser dialog to server */ private function fileSelected(evt:Event):void { fileRef.upload(new URLRequest(FILE_UPLOAD_URL), "uploadFile"); } /** * load uploaded file from server into flash */ private function uploadCompleted(evt:Event):void { var uploadedFileUrl:String = UPLOADED_XML_URL + fileRef.name; var message:String; var loader:URLLoader = new URLLoader(); loader.addEventListener(Event.COMPLETE, downloadInFlashCompleted); loader.load(new URLRequest(uploadedFileUrl)); } /** * file has been completely loaded into Flash. You can now do with it * whatever you want to do. */ private function downloadInFlashCompleted(evt:Event):void { trace(evt.target.data); } |
The script at http://your-server.com/path/to/upload/flashUpload.php should look like this:
1 2 3 4 5 6 7 | <?php move_uploaded_file($_FILES['uploadFile']['tmp_name'], $_FILES['uploadFile']['name']); #return something to flash. Otherwise the Event.Complete #listener will not trigger. echo "somethingThatFlashGetsAResponseToItsRequest."; ?> |