Subscribe: Posts / Comments / Email


RSS

Adobe Flex – File Upload and Download

Wed, Oct 8, 2008

Flex, Tutorials

Have you ever wanted to be able to upload a file in Flex? Or how about download a file in Flex? Well I am going to provide the code to do just that.

With Adobe Flex’s sandbox issues I could only get this to work inside Air, but working with the web browser I kept on getting an IOError. I thought it could have been the write permissions on the folder but it wasn’t.

I even put a crossdomain file and Security.AllowAll("*") but that didn’t help at all. So if you want to send uploads with Air this will be perfect, other than that someone help me figure out this security issue.

Ok here is the Flex code for the three components you will use to build this application.

Here is the item renderer ImageRenderer.mxml:

		

		
		
		
	

Here is the download component FileDownload.mxml:


	
		
			

		
		

		
		
			
				
					
				
			
			

		
		
	

Here is our second component FileUpload.mxml:


	
		
			
		

			
			
				
				
			

			
			

			
			
					
					
					
			
		
		
				
				

				
				

				
				
		
	

And our main view Chapter5.mxml: ( From my guide )

	
		
			
		

		

	

For the back-end we are using PHP, so we have two scripts here one is for processing the upload and then outputting XML with the results, and one for getting the data from the database for the display in XML.

flex_file_upload.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 = "\n";

	/* Set the root node for the xml */
	$xml_output .= "\n";

	/* If file was moved and inserted */
	if ( $result )
	{
		/* Build the XML if file was successful */
		/* Set the child node */
	    $xml_output .= "\t\n";

	    /* status */
	    $xml_output .= "\t\t" . "Successful" . "\n";

	    /* file_name variable */
	    $xml_output .= "\t\t" . $file_name . "\n";

	    /* file_size variable */
		$xml_output .= "\t\t" . $file_size . "\n";

		/* file_type variable */
		$xml_output .= "\t\t" . $file_type . "\n";

		/* file_url variable */
		$xml_output .= "\t\t" . $file_url . "\n";

	    /* Close the child result now and print the child result node out */
	    $xml_output .= "\t\n";

	}

	} else {

		/* Set the content type for the browser */
		header("Content-type: text/xml");

		/* Set the header xml version */
		$xml_output = "\n";

		/* Set the root node for the xml */
		$xml_output .= "\n";

		/* Build the XML if file was un-successful */
		/* Set the child node */
	    $xml_output .= "\t\n";

	    /* status */
	    $xml_output .= "\t\t" . "Error" . "\n";

	    /* file_name variable */
	    $xml_output .= "\t\t" . $file_name . "\n";

	    /* file_name variable */
	    $xml_output .= "\t\t" . "There was a problem uploading your file." . "\n";

	    /* Close the child result now and print the child result node out */
	    $xml_output .= "\t\n";

	}

	/* Close the parent results node */
	$xml_output .= "";

	/* Output all of the xml */
	echo $xml_output; 

flex_file_download.php:

	/** ****************************************************************
	 * Working File Download XML Server Script for Flex
	 *
	 * MySnippets
	 * Free for use
	 *
	 * @author  Jonnie Spratley
	 * @contact jonniespratley@gmail.com
	 ******************************************************************* */
	/* Set the content type for the browser */
	header("Content-type: text/xml");

	/* 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() );

	/* Build the query for the table */
	$query = "SELECT * FROM flex_uploads ORDER BY file_date DESC";

	/* Execute the query on the table */
	$resultID = mysql_query( $query, $link ) or die( "Data not found." );

	/* Set the header xml version */
	$xml_output = "\n";

	/* Set the root node for the xml */
	$xml_output .= "\n";

	/* Loop through all records in the query and output */
	for( $x = 0 ; $x < mysql_num_rows( $resultID ) ; $x++ )
	{
		/* Result rows */
	    $row = mysql_fetch_assoc( $resultID );

		/* Set the child node */
	    $xml_output .= "\t\n";

		/* Set every node inside the child file node (id) */
	    $xml_output .= "\t\t" . $row['file_id'] . "\n";

	    /* file_name table column */
	    $xml_output .= "\t\t" . $row['file_name'] . "\n";

	    /* file_size table column */
		$xml_output .= "\t\t" . $row['file_size'] . "\n";

		/* file_type table column */
		$xml_output .= "\t\t" . $row['file_type'] . "\n";

		/* file_url table column */
		$xml_output .= "\t\t" . $row['file_url'] . "\n";

		/* file_date table column */
		$xml_output .= "\t\t" . $row['file_date'] . "\n";

	    /* Close the child file now and print the child file node out */
	    $xml_output .= "\t\n";

	}/* Ends the loop */

	/* Close the parent files node */
	$xml_output .= "";

	/* Output all of the xml */
	echo $xml_output; 

I hope that this was some great help for people building application where uploading it a must.

Tags: , ,

8 Comments For This Post

  1. José Carlos Fonseca Says:

    Hello!! I´m trying use this code but i can´t put working. Can you help me? Can you put a demo here?

    Thank you.

  2. Jonnie Says:

    Ya, I will try to get that up soon, what is wrong with the app? I know that for some reason when you run the code on a live server it gets a IO error.

  3. MechanisM Says:

    hmm..nice code!! but where’s sql file? or example?

  4. Jonnie Says:

    Ya, I gave the source code to download, did you not get it?

  5. Kenny Says:

    yo, here is a simple way to do both via flex and php.

    //upload php script - name this test_file_upload.php
    
    //download script - name this test_file_download.php
    
    //now the flex; use onUpload() and onDownload() functions
    
    			import flash.events.IOErrorEvent;
    			import flash.net.navigateToURL;
    
    			private var fileRef:FileReference;
    			private function onUpload():void {
    				fileRef = new FileReference();
    				fileRef.addEventListener(Event.SELECT, selectHandler);
    				fileRef.addEventListener(Event.COMPLETE, completeHandler);
    				fileRef.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
    				try
    				{
    				    var success:Boolean = fileRef.browse();
    				}
    				catch (error:Error)
    				{
    				    trace("Unable to browse for files.");
    				}
    			}
    			private	function selectHandler(event:Event):void
    				{
    					var request:URLRequest = new URLRequest("http://localhost/test_file_upload.php");
    				    try
    				    {
    				    	fileRef.upload(request);
    					}
    				    catch (error:Error)
    				    {
    				        trace("Unable to upload file.");
    				    }
    				}
    			private function completeHandler(event:Event):void
    			{
    					trace("uploaded");
    			}
    			private function onIOError(event:IOErrorEvent):void {
    				trace (event.text);
    			}
    			private function onDownload():void {
     				var urlReq:URLRequest = new URLRequest("http://localhost/test_file_download.php");
     				navigateToURL(urlReq);
     			}
    
  6. eom Says:

    if you want to work with the web browser, You can be accessed by a html file.
    like this..
    ############################################
    #
    #
    #
    #
    #
    #
    #
    #
    #
    #

  7. santiago Says:

    great example!

    now, I need the files to be in a secure area, only accesible via my FLEX app…. what should I do? how can I store the files in my MySQL database and download them directly from it? and not get a URL that anyone could copy and then download my file without login in to my FLEX app.

    thanks!!

  8. Monte Says:

    Is there a way to execute uploaded data at back end to generate a graph in front end?

Leave a Reply