Home arrow PHP arrow Page 6 - Building a Flex Multiple File Uploader with Image Preview

Error Event - PHP

As the Internet integrates itself more and more into our daily lives, we see the popularity of electronic media spread like a virus. Websites like Youtube and Flickr have had a great deal of success by primarily focusing on user-generated content. Because so many people are uploading media, making the process as easy as possible makes the most sense. Keeping reading to see how Flex can do this for you.

TABLE OF CONTENTS:
  1. Building a Flex Multiple File Uploader with Image Preview
  2. Selecting Files
  3. Getting the Files
  4. Uploading
  5. Listening for Upload Events
  6. Error Event
By: Keith Lee
Rating: starstarstarstarstar / 6
December 04, 2009

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

If an error occurs, our uploadError method will be called.  Here is the code:

private function uploadError(event:Event):void{

    

    currentFile.progress="Error!";

    uploadQueue.itemUpdated(currentFile); // force a refresh

    // find the next upload

    uploadNextFile();

}

In this method we just update the progress property to "Error!", update the DataGrid and look for the next upload.

PHP Upload Script

<?php

$MAXIMUM_FILESIZE = 1024 * 1000; 

if ($_FILES['Filedata']['size'] <= $MAXIMUM_FILESIZE)

{

    $move_result = move_uploaded_file($_FILES['Filedata']['tmp_name'], 

                                                    "./flexFiles/" . 

                                                    $_GET['id'] . "_" .

                                                    $_FILES['Filedata']['name']);

    error_log("moving file: " . $_FILES['Filedata']['tmp_name'],3,"/tmp/upload.log");

}else{

    error_log("file to large: " . $_FILES['Filedata']['tmp_name'],3,"/tmp/upload.log");

}

The upload script is very simple.  For our demonstration, we are not checking the number of files and user identity.  These steps, as well as other security precautions, should be taken before using this file in a product environment.  For more information on PHP uploading, see http://us3.php.net/manual/en/features.file-upload.php.

In Closing

In less than 200 lines of code, we were able to create a Flex uploader with image preview which runs on multiple platforms.  There are somes parts of the process which are a bit complicated, but with some study this article should provide an excellent guide to building your own custom uploader.  

This code can be furthered by making note of the ability of Flash Player 10's FileReference Object which can read and write files locally to your computer. This can improve the efficiency of your application by allowing a preview of your images before uploading them to the server.

Here are some links that you may find interesting:

http://www.adobe.com/products/flex/

http://www.adobe.com/products/player_census/flashplayer/

http://livedocs.adobe.com/flex/3/html/help.html?content=dpcontrols_6.html

http://livedocs.adobe.com/flex/3/html/help.html?content=cellrenderer_3.html

http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_7.html

Complete Code:

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 

           paddingTop="5"

           paddingLeft="5"

           paddingRight="5"

           paddingBottom="5"

           layout="vertical"

           creationComplete="init()">

<mx:Panel width="100%" 

     height="100%" 

     title="Upload List" 

     horizontalAlign="center">

<mx:DataGrid id="fileList" width="100%" height="100%" rowHeight="50"

        dataProvider="{uploadQueue}">

<mx:columns>

<mx:DataGridColumn headerText="Filename" dataField="name"/>

<mx:DataGridColumn headerText="Progress" dataField="progress"/>

<mx:DataGridColumn headerText="Preview"  

              width="65"

              dataField="preview" 

              itemRenderer="mx.controls.Image">

</mx:DataGridColumn>

</mx:columns>

</mx:DataGrid>

<mx:ControlBar>

   <mx:HBox width="100%" horizontalAlign="center">

    <mx:ButtonBar horizontalGap="2" itemClick="buttonHandler(event)">

   <mx:dataProvider>

   <mx:Object label="Select Files"/>

   <mx:Object label="Start Upload"/>

   </mx:dataProvider>

   </mx:ButtonBar>

   </mx:HBox>

</mx:ControlBar>

</mx:Panel>

<mx:Script>

<![CDATA[

// Imports

import mx.events.ItemClickEvent;

import flash.net.FileReference;

import flash.net.FileReferenceList;

import mx.collections.ArrayCollection;

import flash.net.FileFilter;

   // Constants

   public const imageUrl:String = "http://dev/flexFiles/";

   public const uploadPath:String = "http://dev/flexUploader.php?id=";

   

// Properties

public var uploadList:FileReferenceList;

private var uploadURL:URLRequest;

private var currentFile:Object;

private var imageTypes:FileFilter;

[Bindable] public var uploadQueue:ArrayCollection = new ArrayCollection();

public function init():void{

// create an instance of the File Reference List

uploadList = new FileReferenceList();

uploadList.addEventListener(Event.SELECT,populateDataGrid);

// set the upload URL

uploadURL = new URLRequest();

           // set the file filter type

           imageTypes = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");

             

             }

private function buttonHandler(event:ItemClickEvent):void{

       

       switch(event.label){

       

        case 'Select Files':

          uploadList.browse([imageTypes]); 

        break;

       

        case 'Start Upload':

          uploadNextFile();

        break;

       }

}

private function populateDataGrid(event:Event):void{

   // remove any previous entries in the upload list

   uploadQueue.removeAll();

   

   // add all the new items

   for each( var file:FileReference in uploadList.fileList){

    uploadQueue.addItem({name:file.name,

                        progress:'Ready',

                        preview:'',

                        fileRef:file});

   }

}

private function uploadNextFile():void{

   var file:FileReference;

  

   // get the next file from the queue

   for each(var o:Object in uploadQueue){

                    

                    

                    // if we find a ready status, then start the upload

                    if (o.progress=="Ready"){

                     // save the current object for updating

                     currentFile= o;

                    

                     // update the progress

                     o.progress="Initializing Upload";

                     uploadQueue.itemUpdated(currentFile); // force a refresh

                    

                     // grab the file reference

                     file = o.fileRef;

                    

                     // add event listeners

                     file.addEventListener(Event.COMPLETE, uploadComplete);

                     file.addEventListener(ProgressEvent.PROGRESS, uploadProgress);

                     file.addEventListener(IOErrorEvent.IO_ERROR, uploadError);

                    

                        // generate an ID for this upload

                        o.uploadId=Math.round(Math.random() * (5000 - 1000));

                        

                     // upload the file

                     uploadURL.url = uploadPath + o.uploadId ;

                     file.upload(uploadURL);

                    

                     return;

                    }    

                      

   }

   

  uploadQueue.itemUpdated(currentFile); // force a refresh

}

private function uploadComplete(event:Event):void{

// Mark the upload as completed

currentFile.progress="Complete: " + currentFile.progress;

// set the uploaded image src

currentFile.preview=imageUrl + 

                   currentFile.uploadId + "_" +

                   currentFile.fileRef.name;

// find the next upload

uploadNextFile();

}

private function uploadProgress(event:ProgressEvent):void{

currentFile.progress = event.bytesLoaded + " of " + event.bytesTotal;

uploadQueue.itemUpdated(currentFile);

}

private function uploadError(event:Event):void{

currentFile.progress="Error!";

uploadQueue.itemUpdated(currentFile); // force a refresh

// find the next upload

uploadNextFile();

}

]]>

</mx:Script>

</mx:Application>





 
 
>>> More PHP Articles          >>> More By Keith Lee
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: