DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Flex And PHP File Upload
Here is the php
<?php
/** *******************************************************************
* Working File Upload Server Script for Flex
*
* MySnippets
* Free for use
*
* @author Jonnie Spratley
* @contact jonniespratley@gmail.com
******************************************************************* */
if (isset( $_POST['FileType']) && isset($_FILES['Filedata']) )
{
/* Establish a connection to database */
$link = mysql_connect('localhost', 'spratley_guest', 'guest') or die('Could not connect: ' . mysql_error());
/* Select the database */
mysql_select_db( 'spratley_tutorials', $link ) or die ( mysql_error() );
/* Set the upload directory */
$upload_dir = "uploads/";
/* PHP temp_name variable for file upload */
$temp_name = $_FILES['Filedata']['tmp_name'];
/* PHP file_name variable sent from Flex */
$file_name = $_FILES['Filedata']['name'];
/* PHP file_size variable sent from Flex */
$file_size = $_FILES['Filedata']['size'];
/* PHP file_type variable sent from Flex */
$file_type = $_FILES['Filedata']['type'];
/* PHP file_ext variable set from Flex */
$file_ext = $_FILES['Filedata']['extension'];
/* Set the file_url to the hosturl and the updload directory and filename */
$file_url = $_SERVER['HTTP_HOST'] . $upload_dir . $file_name;
/* Replace any computer garbage */
$file_name = str_replace("\\","",$file_name);
/* Replace any garbage */
$file_name = str_replace("'","",$file_name);
/* Set up the filepath */
$file_path = $upload_dir.$file_name;
/* Insert info into fle_uploads table in your mysql database */
$insert = "INSERT INTO flex_uploads ( file_name, file_size, file_type, file_ext, file_url )
VALUES ( '$file_name',
'$file_size',
'$file_type',
'$file_ext',
'$file_url' )";
/* Execute the query */
$query = mysql_query($insert) or die(mysql_error());
/* Get the last insert id */
$lastid = mysql_insert_id();
/* Move the uploaded file */
$result = move_uploaded_file( $temp_name, $file_path );
/* Set the content type for the browser */
header("Content-type: text/xml");
/* Set the header xml version */
$xml_output = "<?xml version=\"1.0\"?>\n";
/* Set the root node for the xml */
$xml_output .= "<results>\n";
/* If file was moved and inserted */
if ( $result )
{
/* Build the XML if file was successful */
/* Set the child node */
$xml_output .= "\t<result>\n";
/* status */
$xml_output .= "\t\t<status>" . "Successful" . "</status>\n";
/* file_name variable */
$xml_output .= "\t\t<name>" . $file_name . "</name>\n";
/* file_size variable */
$xml_output .= "\t\t<size>" . $file_size . "</size>\n";
/* file_type variable */
$xml_output .= "\t\t<type>" . $file_type . "</type>\n";
/* file_url variable */
$xml_output .= "\t\t<url>" . $file_url . "</url>\n";
/* Close the child result now and print the child result node out */
$xml_output .= "\t</result>\n";
}
} else {
/* Set the content type for the browser */
header("Content-type: text/xml");
/* Set the header xml version */
$xml_output = "<?xml version=\"1.0\"?>\n";
/* Set the root node for the xml */
$xml_output .= "<results>\n";
/* Build the XML if file was un-successful */
/* Set the child node */
$xml_output .= "\t<result>\n";
/* status */
$xml_output .= "\t\t<status>" . "Error" . "</status>\n";
/* file_name variable */
$xml_output .= "\t\t<name>" . $file_name . "</name>\n";
/* file_name variable */
$xml_output .= "\t\t<message>" . "There was a problem uploading your file." . "</message>\n";
/* Close the child result now and print the child result node out */
$xml_output .= "\t</result>\n";
}
/* Close the parent results node */
$xml_output .= "</results>";
/* Output all of the xml */
echo $xml_output;
?>
Here is the Flex.
<?xml version="1.0" encoding="utf-8"?>
<!--
/** *******************************************************************
* MySnippets
* Free for use
*
* @author Jonnie Spratley
* @contact jonniespratley@gmail.com
******************************************************************* */
-->
<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml"
title="Upload a File"
showCloseButton="true"
close="PopUpManager.removePopUp( this )"
creationComplete="init()" width="450" height="200" cornerRadius="10">
<mx:Script>
<![CDATA[
import mx.managers.PopUpManager;
import flash.net.*;
import mx.controls.*;
/* Location of our Upload script */
private static const UPLOAD_URL:String = "php/flex_file_upload.php";
private static const IMAGE:String = "image";
private static const MODE_BROWSE:String = "fileModeBrowse";
private static const MODE_UPLOAD:String = "fileModeUpload";
[Bindable]public var fileMode:String;
private var maxFileSize:Number = 3500;
private var fileReference:FileReference;
private var fileFilter:FileFilter;
private var fileType:String;
private var isReady:Boolean;
/* Set up our application */
private function init():void
{
Security.allowDomain( "*" );
Security.loadPolicyFile( "crossdomain.xml" );
PopUpManager.centerPopUp( this );
this.isPopUp = false;
//Set up the file upload components
fileMode = "";
pb_progress.label = "Select File Type";
fileReference = new FileReference();
addListeners();
}
/* Register all of our event handlers and listeners */
private function addListeners():void
{
fileReference.addEventListener( Event.CANCEL, cancelHandler );
fileReference.addEventListener( Event.SELECT, selectHandler );
fileReference.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
fileReference.addEventListener( ProgressEvent.PROGRESS, progressHandler );
fileReference.addEventListener( Event.COMPLETE, completeHandler );
}
/* We can assign the correct file filters based on the selected check box */
private function assignFileType( event:Event ):void
{
//We switch depending on the id of the check box that is selected
switch ( event.currentTarget.id )
{
//If the id is image
case "cb_image":
//Set varable to check if the cb_image box is selected
var image_selected:Boolean = ( cb_image.selected ) ? true : false;
if( image_selected != false )
{
//Enable the button
isReady = true;
//Set the fileType to image
fileType = "image";
//Display to user to browse
pb_progress.label = "Browse for File";
//Filter the files based on fileType
filterFileType();
} else {
//Else disable the button
isReady = false;
}
break;
//If the id is a document
case "cb_document":
var document_selected:Boolean = ( cb_document.selected ) ? true : false;
if ( document_selected != false )
{
//Enable the button
isReady = true;
//Set the fileType to document
fileType = "document";
//Display to user to browse
pb_progress.label = "Browse for File";
//Filter the files based on fileType
filterFileType();
} else {
//Else disable the button
isReady = false;
}
break;
//If the id is a compressed
case "cb_compressed":
var compressed_selected:Boolean = ( cb_compressed.selected ) ? true : false;
if ( compressed_selected != false )
{
//Enable the button
isReady = true;
//Set the fileType to document
fileType = "compressed";
//Display to user to browse
pb_progress.label = "Browse for File";
//Filter the files based on fileType
filterFileType();
} else {
//Else disable the button
isReady = false;
}
break;
}
}
/* Filter the different filetypes */
private function filterFileType():void
{
switch ( fileType )
{
case "image":
fileFilter = new FileFilter( "Images (*.jpg; *.jpeg; *.gif; *.png;)",
"*.jpg; *.jpeg; *.gif; *.png" );
break;
case "document":
fileFilter = new FileFilter( "Documents (*.pdf; *.txt; *.doc; *.rtf;)",
"*.pdf; *.txt; *.doc; *.rtf;" );
break;
case "compressed":
fileFilter = new FileFilter( "Compressed (*.zip; *.rar; *.7zip;)",
"*.zip; *.rar; *.7zip;" );
break;
}
}
/* Submit the file to check if its legit */
private function submit( _fileMode:String ):void
{
fileMode = _fileMode;
if ( isReady != true )
{
Alert.show("Please select a file type!","ALERT", Alert.OK);
} else if ( fileMode == MODE_BROWSE )
{
openBrowseWindow();
} else if ( fileMode == MODE_UPLOAD )
{
uploadFile();
}
}
/* Open up the browse for file window */
private function openBrowseWindow():void
{
try
{
fileReference.browse([fileFilter]);
}
catch ( illegalOperation:IllegalOperationError )
{
Alert.show( String(illegalOperation.type), "illegal operation error", 0);
}
}
/* Our select handler for checking the filesize, etc */
private function selectHandler( event:Event ):void
{
//Get the filesize
var fileSize:Number = Math.round( fileReference.size/1024 );
//Set the filename input to the filename of the file
txt_filename.text = fileReference.name;
//Set the filesize text to the size of the file for upload
txt_filesize.text = String( fileSize ) + "kb";
//If the current file size is less or equal to our max file size then up
if ( fileSize <= maxFileSize )
{
//Set the fileMode to upload
fileMode = MODE_UPLOAD;
//Set the label on the progress bar
pb_progress.label = "Click Upload";
} else {
//If the file is to big, alert the user
Alert.show( String("File is to large! \n\nPlease select a file smaller than "+ fileSize + "kb" ),
"File Size Error", Alert.OK );
}
}
/* Sends the file to our script */
private function uploadFile():void
{
var request:URLRequest = new URLRequest();
request.url = UPLOAD_URL;
var params:URLVariables = new URLVariables();
params.FileType = fileType;
request.method = URLRequestMethod.POST;
request.data = params;
fileReference.upload( request );
}
/* Handles our progress bar */
private function progressHandler( event:ProgressEvent ):void
{
//Set the progress to our bytesLoaded, and bytesTotal
pb_progress.setProgress( event.bytesLoaded, event.bytesTotal );
//Set the label to uploading and do alittle math of displaying the current progress
pb_progress.label = "Uploading " + Math.round( event.bytesLoaded / 1024 ) + " kb of " +
Math.round( event.bytesTotal / 1024 ) + " kb ";
}
/* Just incase our user wants to cancel the upload */
private function cancelUpload():void
{
//Cancel the fileref
fileReference.cancel();
//Reset the uploader
resetUploader();
//Remove the popup
PopUpManager.removePopUp( this );
}
/* We can handle the canceled download */
private function cancelHandler( event:Event ):void
{
Alert.show( "File Upload Cancelled" );
}
/* IO Error handler */
private function ioErrorHandler( event:IOErrorEvent ):void
{
//Alert of the error
Alert.show( String( event.type ), "IOError", 0 );
//Reset the uploader
resetUploader();
}
/* Complete handler */
private function completeHandler( event:Event ):void
{
var file:FileReference = FileReference( event.target );
var fileURL:String = file.name;
//Show the user the uploaded file
Alert.show( String( fileURL ), "File Uploaded", Alert.OK );
//Reset the uploader
resetUploader();
}
/* Reset the filemode, inputs, progress bar and selected check boxes */
private function resetUploader():void
{
fileMode = "";
isReady = false;
txt_filename.text = "";
txt_filesize.text = "";
pb_progress.label = " Select File Type";
pb_progress.maximum = 0;
pb_progress.minimum = 0;
}
]]>
</mx:Script>
<mx:Form width="100%" height="100%">
<!--File that is going to be uploaded-->
<mx:FormItem label="File name:" required="true" direction="horizontal" width="100%">
<mx:TextInput id="txt_filename"
width="100%"/>
<mx:Button id="btn_browse"
label="Browse"
click="submit( MODE_BROWSE )"/>
</mx:FormItem>
<!--Size of the file to upload-->
<mx:Text id="txt_filesize" color="#000000" width="100%"/>
<!--Type of file to upload-->
<mx:FormItem label="Type of Upload:" required="true" width="100%" direction="horizontal">
<mx:CheckBox id="cb_image"
click="assignFileType( event )"
label="Image"/>
<mx:CheckBox id="cb_document"
click="assignFileType( event )"
label="Document"/>
<mx:CheckBox id="cb_compressed"
click="assignFileType( event )"
label="Compressed"/>
</mx:FormItem>
</mx:Form>
<mx:ControlBar>
<!--Cancel Button-->
<mx:Button id="btn_cancel"
label="Cancel"
click="cancelUpload()"/>
<!--Progress Bar-->
<mx:ProgressBar id="pb_progress"
labelPlacement="center"
trackHeight="8"
width="100%"/>
<!--Upload Button-->
<mx:Button label="Upload"
id="upload_btn"
click="submit( MODE_UPLOAD )"
enabled="{ fileMode == MODE_UPLOAD }"/>
</mx:ControlBar>
</mx:TitleWindow>





Comments
Snippets Manager replied on Sat, 2010/07/10 - 2:27am