Wednesday, March 23, 2011

Upload File From Flex to PHP

MXML File

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init();" backgroundGradientAlphas="[1.0, 1.0]" backgroundGradientColors="[#4E4C4C, #4E4C4C]">
    <mx:Script>
        <![CDATA[
           
            import mx.controls.Alert;
            private var urlRequest:URLRequest;
            private var fileReferenceList:FileReferenceList;
            private var serverSideScript:String = "http://localhost/testfile/uploadFile.php";
           
       
            private function init():void {
           
                fileReferenceList = new FileReferenceList();
                fileReferenceList.addEventListener(Event.SELECT, fileSelectedHandler);
            }
           
            private function uploadFile():void {
                fileReferenceList.browse();
            }
           
            private function fileSelectedHandler(event:Event):void {
                urlRequest = new URLRequest(serverSideScript);
                var fileReference:FileReference;
                var fileReferenceList:FileReferenceList = FileReferenceList(event.target);
                var fileList:Array = fileReferenceList.fileList;

                // get the first file that the user chose
                fileReference = FileReference(fileList[0]);
               
                // upload the file to the server side script
                fileReference.addEventListener(Event.COMPLETE, uploadCompleteHandler);
                fileReference.upload(urlRequest);
               
                // update the status text
                statusText.text = "Uploading...";
            }
           
            private function uploadCompleteHandler(event:Event):void {
                statusText.text = "File Uploaded: " + event.target.name + event.target.size;
            }

           
        ]]>
    </mx:Script>
   
    <mx:Label text="Upload File From Flex to PHP" fontWeight="bold" color="#FEFFFF" fontSize="23"/>
    <mx:Label text="Choose a file..." id="statusText" color="#FCFDFD" fontSize="17"/>
    <mx:Button click="uploadFile();" label="Upload File"/>
    </mx:Application>


PHP Server Side File

<?php
$url = "D:/uploads/"; //This is Upload file URL
$tempFile = $_FILES['Filedata']['tmp_name'];   // This is going to return the temporary file location
$fileName = $_FILES['Filedata']['name'];  // This is going to return the name.
$fileSize = $_FILES['Filedata']['size'];  // This is going to return the file size in bytes
move_uploaded_file($tempFile, $url.$fileName); //This is going to upload file to your folder
?>

Output







No comments:

Post a Comment