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. 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!!

  7. Monte Says:

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

  8. Rubin Gabeline Says:

    OIOPublisher is an Ad management service that helps us maximize our revenue, save our precious time, keep our ad space in our control. OIO Publisher uses a PHP Script to sell and serve ads on your website. It can be used on Standard websites and on both Blogger and WordPress blogs which are hosted on their own domains.

    We can customize our advertise space to great extent with this ad management network. We can create lots of options like number of ads available and of different formats, can show rotating ads, payment methods like paypal. Credit card, advertising option available on month basis or can be booked for several months at a time etc. All of these tasks can be performed quite easily using the Admin panel available when we purchase their services. When someone click on any of “Advertise here” banner or link available on your website, will be taken to the advertising sales page. Once they fill all the information about their website, chose their mode of payment and get approval from us, OIO Publisher will start showing their ads for a fixed period of time and will start sending ads performance statistics to the advertisers on weekly basis.
    The total cost of OIOPublisher is only $47 and once you have this advertising service at you, can use on your multiple websites and blogs. You will get a discount of $10 if you buy this ad management software through my affiliate link and using my coupon code SOLAR-X (this official code is also provided on OIOpublisher’s main site). So you will be getting it for $37 only for lifetime. This coupon code is valid for the month of July 2010 only.

    Contact me if you decide to buy their services and need help or simply click on my name as I will update the following link every month: http://www.oiopublisher.com/ref.php?u=1585 – you will get the discount (highest available online) only through my affiliate link.

    OIOPublisher is a must for you if you are thinking of making money online selling advertising space on your website or blog. It can be used as a plugin on all WordPress blogs that are hosted on their own domains. They have a big marketplace that advertisers use to find good websites and blogs to advertise their websites and services in the form of banners, links and paid reviews. Once you buy a copy of OIOPublisher, you will be able to submit all of your websites and blogs in relevant categories available in their marketplace.

Leave a Reply