What is Flash Uploader?

It's a browser control built using Adobe Flash technology. It is meant to replace HTML's very limited <input type=“file”> tag.

Why replace <input type=“file”>? It's awkwardly uncustomisable (try changing style on that “Browse” button) and it's very inconvenient. You don't see what's going on when uploading files, there is no way to display upload progress, and you get upload error only when your form is completely submited to the server and all the files are uploaded. That's a no good scenario… at least in our books.

That's where Flash Uploader comes in. It displays neat progress indicator, it does many file verification routines (filetype, max size) on client-side and it's customisable beyond recognition, both visually and functionally.

Requirements

  • Adobe Flash Player 8.0 or later
  • PHP 4.3.x or later (only needed if used with a PHP backend)

Usage

Installation

1. Extract the contents of Flash Uploader's package to some directory on your web server

I.e.: uploader

2. If necessary set write permissions on subdirectories:

uploader/tmp

uploader/uploads

This can be done using chmod command on *nix OS'es or through most FTP clients.

3. Edit config.xml and config.php files (see later sections)

Principles

Flash Uploader works by replacing <input type=“file”> tag. The biggest difference is that files are being uploaded to server not with the form but separately - before form submits.

The most common use of Flash Uploader is form “hijacking”. Flash Uploader's accompanying JavaScript captures HTML form's submit event and delays it until files are finished uploading to server by Flash components, then initiates form submition. If used in conjunction with a supplied PHP backend it also injects info about uploaded into $_FILES collection so you don't see much of a difference on server-side. (there actually are some minor differences; read about them later in this document)

However Flash Uploader is not limited to form hijacking. You can disable it and manage all uploading yourself using Flash Uploader's JavaScript interface. Or you can have no HTML forms at all. Your call. Read on to find out how.

Frontend configuration (config.xml)

Most of the front-end (or Flash movie) is controlled through XML config file config.xml. Let's overview it's contents.

Settings that affect functionality

maxsize

Maximum allowed file size in bytes. Flash Uploader will display an error and prevent uploading from starting if the selected file is bigger than this.

filetypes

Add present file types you want to be used when selecting files to upload in your “Files of type” dropdown:

Separate individual file extensions by commas.

<filetypes>
	<type>
		<description>All files</description>
		<extension>*.*</extension>
		<mactype>*</mactype>
	</type>
	<type>
		<description>Video Files</description>
		<extension>*.avi;*.mpg;*.mov;*.wmv</extension>
		<mactype>FLV</mactype>
	</type>
	<type>
		<description>Image files</description>
		<extension>*.jpg;*.gif;*.png</extension>
		<mactype>JPEG;jp2_;GIFF</mactype>
	</type>
</filetypes>

prompts

Language prompts and their translations. You should provide a translation for each language you are planning to use. If specific prompt for the selected language is missing Flash Uploader will fall back and display english text instead.

<prompts>
  <select_file>
  	<en>Select a File</en>
  	<fr>Sélectionner des fichiers</fr>
  	<de>Wählen Sie eine Datei</de>
  </select_file>
  ...
</prompts>

Visual appearance settings

Each visual setting is thouroughly commented in the supplied config.xml file. Therefore we will cover only those aspects of visual appearance configuration that we feel require sample image.

window

This set of settings controls the way control background rectangle looks like. You can control background color (including gradient), border colors and width, corner radius as well as padding. Your can also assign transparency and background image/flash movie for background. Here are several examples:

bgcolor: #CCCCCC; borderwidth: 0 (no-border); borderradius: 10

bgcolor: #CCCCCC; borderwidth: 2; bordercolor: #777777; borderradius: 5

bgcolor: #CCCCCC,#999999 (gradient); borderwidth: 2; bordercolor: #777777; borderradius: 10

layout

This can be either “horizontal” (default) or “vertical”.

horizontal

vertical

NOTE: if Upload/Cancel buttons are turned off (explained further) this setting has no effect whatsoever.

upload / cancel

These settings control if and how Upload and Cancel buttons are displayed.

Leave width and height settings blank for Flash Uploader to decide on the size automatically.

NOTE: It makes sense to disable Upload button if you are hijacking an HTML form. Clicking Upload button in Flash Uploader will not trigger form submit event.

progress

This group of settings defines visual appearance of the file selector / progress bar control in Flash Uploader. Read further for explanation.

progress.width / progress.height

Width and height respectively of the file selector / progress bar control. If left blank Flash Uploader will calculate it automatically to take all remaining horizontal and/or vertical area.

progress.select

This settings group defines how file selection control looks and behaves like. The settings and their behaviour is identical to window settings except for a button.

progress.select.button = yes (button is shown; only button is clickable; text is aligned to the left)

progress.select.button = no (button is hidden; the whole selector area is clickable; text is centered)

NOTE: the select button autosizes to select control's height so it is probably a bad idea to enable configurations with high progress.height setting.

progress.background

This group defines progress bar background. Progress bar is shown whne actual uploading is happening. It also remains there when upload finishes. Please refer to window settings descriptions for typical settings like color and borders.

progress.background.image / progress.background.stretch

In addition to typical settings you can have an image or even anothe Flash movie (SWF) as a background for progress bar. Just set it progress.background.image to point to image/movie url.

Flash Uploader will load an image/movie and center it without resizing. If you want it to be stretched to the dimensions of progress bar, set progress.background.stretch to yes.

In the next example we will use a supplied background image (lib/background_1.gif) without stretching.

progress.background.image = lib/bg1.gif

NOTE: stretching a Flash movie migh not always work as expected since often SWF's have objects outside their viewable areas, or their change dimensions due to animations meanwhile stretching is done based on the first frame appearance.

progress.background.alpha

An opacity for the progress bar / selector control.

progress.bar

This group defines progress bar foreground. The idea is that foreground gradually shifts over background as upload progresses. Most of the settings are identical to backgrounds with an exception of alpha and fill direction.

progress.bar.image / progress.bar.stretch

A link to and external image or Flash movie (SWF) to use as a filler for the bar instead of the solid color.

progress.bar.alpha

Identifies opacity of the foreground. You can have black foreground and 50% opacity (default) and it will produce progress effect by darkening background. Or you can have another image “taking over” background. This might lead to a very entertaining upload process (think empty beer glass slowly filling up with the finest a Lager).

progress.bar.direction

Controls how your progress will fill up. I.e. right will mean that progress bar will start filling up from left and continue to the right. Possible values are: right, left, up, down.

In addition to typical settings you can have an image or even anothe Flash movie (SWF) as a background for progress bar. Just set it progress.background.image to point to image/movie url.

progress.bar.direction = up;

progress.bar.direction = down;

progress.bar.direction = left;

progress.bar.direction = right;

progress.textformat / progress.errorformat

Defines regular text and errors formatting:

colortext color (hex color code)
sizetext size
fontfont name (use device fonts, such as Arial, Times New Roman, Tahoma, Verdana…)
boldyes / no
shadowtext shadow color (hex color code). Leave blank for no shadow

Button appearance settings

As button appearance is highly customizable in Flash Uploader we felt it deserved a separate section.

button

This section holds all settings that define appearance of buttons.

button.defaults

This section defines default settings that are applicable to all button's states (normal, hover, etc). Each state can override the default settings as we will see later on.

button.defaults.width / button.defaults.height

Dimensions of the button in pixels. Please note that if the text does not fit into button it will grow automatically possibly affecting selector / progress bar size.

button.defaults.borderradius

Radius in pixels for rounded corners. Set to 0 (zero) for perfectly square corners.

borderradius = 0
borderradius = 5
borderradius = 10
borderradius = 20

button.defaults.bgcolor

This is a background color for your button. As in all backgrounds in Flash Uploader you can supplied a list of comma-separated color values to produce a neat radient effect.

bgcolor = #438FDB (flat)
bgcolor = #65AAF1,#438FDB,#598ABC (gradient)
bgcolor = #FF0000,#00FF00,#0000FF (crazy gradient)

button.defaults.crystal

Set to “yes” for a “crystal” effect that makes buttons look round and shiny.

Here are a few examples of color schemes without crystal and width:

bgcolor = #65AAF1,#438FDB,#598ABC
crystal = #F7D4B2,#E59A50
bgcolor = #EFAA64,#D88D43,#BA8959
crystal = #F7D4B2,#E59A50
bgcolor = #64EF97,#43D87A,#59BA7C
crystal = #B2F7CB,#50E587
bgcolor = #EF649C,#D8437F,#BA5980
crystal = #F7B2CD,#E5508B
bgcolor = #E6EF64,#CED843,#B3BA59
crystal = #F2F7B2,#DBE550

Backend configuration (config.php)

As in XML this backend configuration file (config.php) is also very well commented.

baseurl

This is important. It's a base URL for Flash Uploader. This can be a relative or absolute URL to a directory where uploader.swf is located.

It will subsequently be passed on to a Flash Uploader and be used as a base URL for loading of external files, such as config.xml, data files and supplemental layout images/SWFs.

This setting however can (and should) be overridden when creating Uploader's PHP class explained later in this documentation.

width / height

Default width and height of the control.

These settings can be overridden when placing Flash Uploader instances.

required

If set to true all Flash Uploader instances will be mandatory - the submission of the form will be canceled if no file is selected to upload. This applies only if hijackForm = true.

This setting can be overridden when placing Flash Uploader instances.

hijackForm

If true Uploader will try to “hijack” enclosing form to catch submit event and delay it until file was successfully uploaded.

This feature will not overwrite any existing onSubmit events and even fire browser's submit event.

This setting can be overridden when placing Flash Uploader instances.

secureUploads

If set to true Flash Uploader will create tokens for each instance of Flash Uploader bound to user's IP address. When handling uploaded file, Flash Uploader will check if it came from a proper instance and corresponding IP address. If it's not it will be rejected.

This is particularly useful for closed-user areas. Your PHP script would generate instances of Flash Uploader only for authenticated users thus preventing outsiders of uploading any files.

verifyUpload

If true Uploader will wait for confirmation from the receving upload script, i.e. indication whether the upload was successful.

It is strongly recommended to use supplied upload.php script or method handleFlashUpload of the SolmetraUploader class. This will ensure that proper result messages will be reported back to the Uploader instance.

If you choose to handle uploads yourselves these are the info that needs to be to be returned to flash by the receiving script:

OK/ERROR:uploaded file / error code

Examples:

  • OK:filname.pdf
  • ERROR:UPLOAD_ERR_INI_SIZE
Error codeMeaning
UPLOAD_ERR_INI_SIZEFile exceeds size limit set on the server
UPLOAD_ERR_FORM_SIZEThe uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form
UPLOAD_ERR_PARTIALThe uploaded file was only partially uploaded
UPLOAD_ERR_NO_FILENo file was uploaded
UPLOAD_ERR_NO_TMP_DIRMissing a temporary folder
UPLOAD_ERR_CANT_WRITEFailed to write file to disk
UPLOAD_ERR_EXTENSIONFile upload stopped by extension
UPLOAD_ERR_UNAUTHORIZEDUnauthorized upload
UPLOAD_ERR_MOVEAn error occured while trying to move uploaded file

Flash Uploader will display a corresponding error message that is defined for each error code for the selected language in config XML.

useOriginalName

Normally for security reasons Uploader stores files on server with a temporary names assuming that your script that does post-processing renames/moves them (all the original data is available by calling getUploadedFiles() method).

However if you set this setting to true, Uploader will store files on your server using their original file names. Depending on what extensions you allow to upload and if upload directory is “visible” through http requests might possess a severe security risk since malicious user might upload a .php file

overwriteExisting

Aplicable only if useoriginalname is set to true. If false Uploader will rename the filename in order not to overwrite an existing file

configUrl

A relative or absolute URL to Uploader frontend config file. Please note that this will be relative to uploader.swf, not the PHP script that displays it.

embedConfig

If true config XML file will be preloaded on server and served to Uploader through HTML object's params preventing Uploader making separate request to web server

language

Language code for prompts (default: en)

This setting can be overridden when placing Flash Uploader instances.

bgcolor

A background color for uploader.swf

This setting can be overridden when placing Flash Uploader instances.

useFileTag

If true Uploader will be replaced with a simple HTML <input type=“file”> tag if browser has JavaScript turned off or has an incompatible flash version (below 8)

fileTagParams

An array of property/value pairs to add to <input type=“file”> tag. I.e.: array('class' ⇒ 'myInput')

allowedExtensions

An array of allowed file extensions. If this is not empty, the files with ONLY listed extensions will be allowed to be uploaded. This list however can be even narrowed down by the disallowEdextensions setting explained below.

disallowEdextensions

An array of disallowed file extensions. If this is not empty, the files with listed extensions will be prevented from the upload even if they're listed in allowedExtensions setting.

stripMultipleExtensions

If true only last extension will be left for the file uploaded; i.e. “malicious.php.gif” will become “malicious.gif”.

It is strongly recommended leaving it set to true since Apache webserver passes files to all of the handlers for each of the extension. Therefore it is easy to disguise a file like “malicious.php.gif” as an image and still have Apache process it as a PHP file if it is accessible through HTTP request.

uploadDir

A directory to put uploaded files into. It is strongly recommended setting this to a directory that is NOT accesible through http requests.

tmpDir

A directory to put temporary files into. Aplicable only if secureUploads=true. It is strongly recommended setting this to a directory that is NOT accesible through http requests.

fileTTL

Number of minutes to keep unclaimed files in uploadDir and tmpDir. gcProbability Percent value of the probability a garbage collector is executed when instantiating Uploader: 0 - never, 100 - every time. Set this to higher number on rarely used pages.

Placing Flash Uploader instances on the page

Using supplied PHP class

<?php
// include SolmetraUploader class
include 'SolmetraUploader.php';
 
// Instantiate the class
$solmetraUploader = new SolmetraUploader(
  './',           // a base path to Flash Uploader's directory (relative to the page) [optional]
  'upload.php',   // path to a file that handles file uploads (relative to uploader.swf) [optional]
  './config.php'  // path to a server-side config file (relative to the page) [optional]
);
 
// display Uploader instance
echo $solmetraUploader->getInstance(
   'myField', 	// the name of the field
   500, 	// width of the Uploader control (optional)
   50, 	 	// height of the Uploader control (optional)
   true, 	// required field (true/false) (optional)
   true, 	// "hijack" HTML form (true/false) (optional)
   'http://www.myhost.com/uploader/uploader.xml', 	 // URL to config XML (optional)
   true, 	// embed config into HTML (true/false) (optional)
   'en', 	// language for the prompts (optional)
   '#ffffff' 	// a background color for Flash object (optional)
);
?>

getInstance will return all of the necessary HTML/JavaScript code needed to place Uploader instance on the page.

None of the getInstance parameters are required but one - field name. The rest of the parameters are replaced by defaults from the config file.

Using without PHP

You can place Uploader instances manually - without the use of PHP. Simply place the following code in the HTML.

<!-- This should be included since it defines an SWFObject class needed for proper placing of Flash elements -->
<script type="text/javascript" src="SolmetraUploader.js"></script>
 
<!-- Hidden form fields are used by Uploader JavaScript to control its behaviour -->
<input type="hidden" name="solmetraUploaderInstance" value="[instance_id]" />
<input type="hidden" id="solmetraUploaderData_[instance_id]" name="solmetraUploaderData[[instance_id]]" value="myUpload" /> <!-- set value to form field name -->
<input type="hidden" id="solmetraUploaderHijack_[instance_id]" value="y" /> <!-- set value to "y" if you want to "hijack" HTML form -->
<input type="hidden" id="solmetraUploaderRequired_[instance_id]" value="y" /> <!-- set value to "y" to prevent form submission if this one is not set -->
 
<!-- Here we create main object and set config parameters -->
<script type="text/javascript">
<!--
   var so = new SWFObject("uploader.swf", "solmetraUploaderMovie_[instance_id]", "500", "50", "8", "#ffffff");
   so.useExpressInstall("expressinstall.swf");
   so.addParam("allowScriptAccess", "always");
   so.addParam("allowFullScreen", "false");
   so.addVariable("language", "en");                     // [optional] language to use for textual prompts
   so.addVariable("baseurl", "./");                      // [optional] will be applied to all eternal calls except uploadurl
   so.addVariable("uploadurl", "upload.php");            // [optional] an url to post files to; relative to uploader.swf
   so.addVariable("config", "uploader.xml");             // [optional] path to front-end configuration file
   so.addVariable("instance", "[instance_id]");          // instance id - should be unique
   so.addVariable("allowed", "");
   so.addVariable("disallowed", "php,php3,php4,php5");
   so.addVariable("verifyupload", "true");
   so.addVariable("configXml", "");
   so.addVariable("maxsize", "2097152");
   so.addVariable("hijackForm", "yes");
   so.addVariable("externalErrorHandler", "SolmetraUploader.broadcastError");
   so.addVariable("externalEventHandler", "SolmetraUploader.broadcastEvent");
   so.write("solmetraUploaderPlaceholder_[instance_id]");
   solmetraUploaderMovie_[instance_id] = document.getElementById('solmetraUploaderMovie_[instance_id]');
//-->
</script>

Just replace [instance_id] with any string without spaces. If you have several instances of Uploader on page, make sure their [instance_id] is different.

Set config parameters with so.AddVariable.

Form "hijacking"

It is recommended to set Uploader to “hijack” an HTML form it is enclosed with. That way it will catch form submit events. It will also prevent form submission if it is set to required and a file has not been selected for upload.

Form “hijacking” will not overwrite any onSubmit events you might have.

Handling file uploads

Using PHP

An upload is handled by the script you specify in your config file. (“upload.php” by default) You can use the supplied upload.php file or make your own that includes following two lines of code:

include 'SolmetraUploader.php';
$solmetraUploader = new SolmetraUploader();
$solmetraUploader->handleFlashUpload();

It will automatically handle file upload for you and broadcast result codes back to Uploaders Flash instance which in turn will populate form hidden fields that are needed for the script handling form submission to know what files were uploaded.

Please note that this is a different script from the one you submit your form to. To easily know what files were uploaded by Uploader use gatherUploadedFiles() method of the SolmetraUploader class:

include 'SolmetraUploader.php';
$solmetraUploader = new SolmetraUploader();
$solmetraUploader->gatherUploadedFiles();

Doing so will populate PHP's own $_FILE preset variable with the file data just like if they came from the form upload itself. The only difference is that you won't be able to use PHP's move_uploaded_files() function.

Without PHP

If you want to use Uploader with other language than PHP you will have to handle uploads by yourself. For that you will have to build a script that handles file uploads from Flash object as well as update your script that receives form submission to gather information about files uploaded through Uploader.

Uploader Flash object contacts upload handling script by making a multibyte POST request. It uses form field SolmetraUploader to pass file information. It also passes its instance ID using POST variable instance.

Your script than handles upload from Flash should respond to flash with either an acknowledgement followed by semicolon and uploaded file name or and error code. Examples of responses:

OK:sample_file.avi
OK:renamedfile
ERROR:UPLOAD_ERR_INI_SIZE
ERROR:UPLOAD_ERR_MOVE

Possible error codes are explained in the section about backend configuration.

Uploader passes info about uploaded files to the form submission receiving script as an array. Each element in the array represents one uploaded file as a string in the form:

form_field_name|temporary_file_name|real_file_name

form_field_nameThis is a form field name that represents this instance of Uploader
temporary_file_nameTemporary name of the uploaded file. Returned by script that handles actual file upload from Flash.
real_file_nameReal file name

It is up to your script to parse this string and move uploaded file accordingly.

Secure uploads explained

File upload is often used in closed, session-regulated environments. The trouble is that Flash does not peruse browser's session cookies and thus cannot maintain a session when contacting file upload handling script. That's where Uploader's secure upload feature comes in. If enabled, each time a page using Uploader instance is generated, Uploader's serverside PHP class generates a unique instance id and logs it on the server along user's IP address. Now the upload handling script will accept uploads ONLY from the logged Uploader instances and only with the same user IP address.

Interfacing and controlling with JavaScript

Uploader provides means to interface with it using JavaScript. It can be useful in many situations, i.e. invoking upload by a “detached” button or displaying upload progress in some other part of the page.

To take advantage of Uploader's JavaScript capabilities make sure that SolmetraUploader.js is included on the page.

<script type="text/javascript" src="SolmetraUploader.js"></script>

Invoking file upload

<script type="text/javascript">
SolmetraUploader.flashTriggerUpload([instance_id]);
</script>

Monitoring upload progress

There are two way to monitor upload progress: by calling SolmetraUploader.flashGetUploadStatus() or by registering your own JavaScript function for event broadcats.

SolmetraUploader.flashGetUploadStatus() can return thsese statuses:

blankNo file has been selected yet
selectedA file has been selected but upload has not yet been started
uploadingUpload in progress
doneUpload is complete
errorAn error has occured (read below about registering for error broadcasts)

You can also register your own function to receive events from Uploader.

<script type="text/javascript">
SolmetraUploader.setEventHandler('myEvent');
function myEvent (instance_id, event_id, data) {
   alert('EVENT: ' + event_id);
}
</script>

Now everytime an noteworthy event occurs in Uploader a function myEvent will be called. The function should take three parameters: instance_id, event_id and data.

event_id can be any of the following:

readyInnitiated when Uploader Flash is loaded and ready for operation
selectedA file was just selected
uploadingInnitiated when there is a progress in upload. Can be innitiated numerous times during upload.
completeUpload is complete
canceledUpload was canceled by user

The last parameter data contains an object with the following properties:

nameName of the selected file
tmp_nameTemporary name (only set after upload as returned by the receiving script)
sizeA size of the selected file in bytes
uploadedBytes uploaded so far

Receiving error notifications

Receiving error notifications works much like event monitoring except there is a different function to register an error handler: SolmetraUploader.setErrorHandler()

The error handler function should accept two parameters: instance id and error description string:

<script type="text/javascript">
SolmetraUploader.setErrorHandler('myError');
function myError (instance_id, error_id) {
   alert('ERROR: ' + error_id);
}
</script>
 
uploader.txt · Last modified: 2009/09/29 17:11 (external edit)
 
Other links:
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki