Uploading files in Flex using the FileReference class
In an earlier example we looked at “Downloading files in Flex using the FileReference class“, but It looks like we haven’t ever looked at file uploads.
The following example shows how you can use the FileReference class’s browse() method to allow users to select and upload a single file to a Web server.
If you want to allow users to upload multiple files at once, you would use the FileReferenceList class instead of FileReference.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/21/uploading-files-in-flex-using-the-filereference-class/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
creationComplete="init();">
<mx:Script>
<![CDATA[
private var fileRef:FileReference;
private const FILE_UPLOAD_URL:String = "http://www.YOUR-WEBSITE-HERE.com/fileref/uploader.cfm";
private function init():void {
fileRef = new FileReference();
fileRef.addEventListener(Event.SELECT, fileRef_select);
fileRef.addEventListener(ProgressEvent.PROGRESS, fileRef_progress);
fileRef.addEventListener(Event.COMPLETE, fileRef_complete);
}
private function browseAndUpload():void {
fileRef.browse();
message.text = "";
}
private function fileRef_select(evt:Event):void {
try {
message.text = "size (bytes): " + numberFormatter.format(fileRef.size);
fileRef.upload(new URLRequest(FILE_UPLOAD_URL));
} catch (err:Error) {
message.text = "ERROR: zero-byte file";
}
}
private function fileRef_progress(evt:ProgressEvent):void {
progressBar.visible = true;
}
private function fileRef_complete(evt:Event):void {
message.text += " (complete)";
progressBar.visible = false;
}
]]>
</mx:Script>
<mx:NumberFormatter id="numberFormatter" />
<mx:Button label="Upload file"
click="browseAndUpload();" />
<mx:Label id="message" />
<mx:ProgressBar id="progressBar"
indeterminate="true"
visible="false" />
</mx:Application>
You’ll notice the previous example doesn’t have a SWF or file upload URL. That would be because I don’t want all of you uploading files to my server. :)
In the previous example, I wrapped the call to fileRef.size in a try..catch block. In ActionScript 3.0, Flash Player throws an error if you attempt to get the size of a zero-byte file.
Peter deHaan
Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
145 Responses to Uploading files in Flex using the FileReference class
Leave a Reply Cancel reply
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


Hi anyone know how to do this with amfphp 1.9 or it’s imposible, im working on air fles sdk 3.5
Thanks
is there a way to populate the fileRef information without calling the browse method? I know where the file is located to upload and I want it to auto-upload in the background without any user intervention
@redseven3,
As far as I know, FileReference actions must be user initiated and cannot be done without any user intervention. Otherwise you would potentially be allowed to write Flex applications that would upload user’s system files without their permission.
Peter
OK, so I can’t avoid the browse window.
Can I prepopulate it with whatever the user typed in, so that all they need to do is press open? (assuming they typed it correctly and it exists of course)
In other words set the path and the file name as the default path and file.
Paul
@Paul Stearns,
As far as I know, no. The user must manually browse and select the file themselves. Otherwise you could probably try pointing to any random system file on the user’s machine and upload the file to a server without their knowledge (after they hit any button).
Peter
So there is no way to set the path/file to browse to when the browse dialog box opens.
It would still display the normal browse dialog, but I would have told it what path to start in and file to display. The user could then change the file or path, or cancel.
I do not see this as a security issue, as the user still gets the normal browse dialog.
Paul
@Paul,
Sorry, I think I misunderstood your original comment. No, I do not believe there is any way to pre-populate the initial folder that is displayed when you browse. You would probably have to file an enhancement request at http://bugs.adobe.com/flashplayer/ if there isn’t an exist request for that. But it would definitely be something at the Player level, not at the Flex SDK level.
Peter
For all the guys using servlets, there is an issue in maintaining sessions with FileReference in Flash. Append ‘;jsessionid=’ + sessionId to get it working.
Murali,
I just ran into the problem where FileReference dosen’t maintain the sessionId. So how do I get the sessionId from within Flex/Flash? Is this a call to FlexGlobals or something else? For all my other requests that I make the sessionId is maintained transparently. I’m using java servlets in the backend.
Thanks
@Reuben,
Did you read the comment just before yours? http://blog.flexexamples.com/2007/09/21/uploading-files-in-flex-using-the-filereference-class/#comment-7838
Peter
Nice Example
Hi,
I m facing a problem when i used a combo box as a item editor in AdvanceDatagrid in flex.
When i click on particular cell then combobox will be visible it is ok but background text mins(advancedatagrid cell text) also visible. which is not looking good.
Please give me a solution if all of u have.
Thank you in advance
Hi,
I have a question about the flex upload. After select multiple file to upload, is posible to remove a file from the list upload before upload?
Thank you in advance for the help
good example, thanks a lot.
if i use xampp with apache web server, an using it in local host … where i must put FILE_UPLOAD_URL:String to where ?
Greeting!
I’m new to flash, so bear with me … When you say “http://www.YOUR-WEBSITE-HERE.com/fileref/uploader.cfm” in the code is that assuming that I’ve got some sort of uploader precompiled in that location? If so where do I get such an uploader? Generally I do not use cold fusion, so is that an issue? I am running IIS on a Windows server … Thanks!
- Bob
@Bob Mandel,
You can change that URL to any PHP script or Java script or ASP script or ColdFusion script that uploads files to the server. I’m a ColdFusion guy, so that’s what I generally stick with. If you are using ColdFusion the “uploader.cfm” script could be as simple as this (which is why I love ColdFusion):
So if you wanted to use that script, then your web server would need to have to have ColdFusion server installed. Otherwise you can go through the 120+ comments and other people posted various code samples for PHP and other languages.
Peter
Great! That sets me on the right path. Appreciate the help Peter!
could you please tell me how you solved the problem. because I am using BlazeDs and not getting how to configure .cfm file or right javascript
Guys
Need your Help…
When FileReferenceList.browse() method is called , it lets the user select multiple files.
Here the concern is that if we want user to select limited specified number of files when same function is called. I tried with “typefilter” property and tFileReferenceList.filelist.length also. Not working.
hi,
I am new to flex..
I am using blazeDs as server would like to upload selected file to the server.
can anyone please tell me how to create javascript file for the same as created .cfm file.
hi,
even if some one provide me .cfm file for blazeDs it will be good..
pls help me..
how to upload the svg images in flex 3 application
how can i upload the vector images using flex
Hi thanks for the article.
I uploaded everything to the server, and tell me who uploaded the file but I look and it has not risen.
the folder to upload things is “subida”, I put in the path php /subida and the permissions to 777, but I can not find the problem.
Any ideas.
Thanks
upload.php
—————-
<?php
$errors = array();
$data = "";
$success = "false";
function return_result($success,$errors,$data) {
echo("");
?>
<?
}
function echo_errors($errors) {
for($i=0;$i
<?php
$errors = array();
$data = "";
$success = "false";
function return_result($success,$errors,$data) {
echo("");
?>
<?
}
function echo_errors($errors) {
for($i=0;$i
<?php
$errors = array();
$data = "";
$success = "false";
function return_result($success,$errors,$data) {
echo("");
?>
<?
}
function echo_errors($errors) {
for($i=0;$i
I have successfully scavanged and tweaked available classes and flex projects to build a flex application that will allow users to upload content to the Amazon S3 cloud, but I have run into a snag. Is there any way to change the name of the destination file when uploading? I have not found any variables that allow changing the name, only a way to access the current name of the fileReference selected item.
Any tips would be greatly apprecaited.
thanks,
Silver Tiger
Hi is there anyway I know the name of the file I upload.
Arul,
You just have to use the FileReference object and then invoke name.
Like:
FileReference ref = new File Reference();
In the selectHandler method just use:
ref.name;
Goto: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html
To all: I wanted to see how to get the absolute path of the file selected?
After the upload, is there a way to return a data string back to Flex from my server side page (upload.cfm), and if so, how do I get that data string in flex.
Hi,
i just started with flash/flex etc. and I have a problem with the filereference.
After uploading my player crashed. On the server site the php file receives the complete file I upload.
I use Mac OS (Lion) and firefox 5.0.1 , Flash-player 10.3.183.5 (last update today without any change)
I already found somthing about a bug that my Script must give some output and this I already do.
Does anybody know a solution?
sorry for y post, I already found my own mistake.
Used the .load() method to load the image I upload into the ram (and display it).
With the complete event after load I started the .upload() method.
Now I found out that the same event fires when the load is compleaded and also when the upload is complete. So I would create a loop.
Just the question why the flash play chrashed instead of looping my upload ????
Thanx
Is there any way to modify the data of a filereference?
I open an Image to the ram with th load() function.
Then I crop it and encode it. But in the end I can’t bring it back to the fileReference for upload.
I also tryed the urlLoader and uploaded the image as Postdata. it worked but then I have no progess event for a status bar.
If anybody has an idea please let me know.
Thanks
Hi. I have a system that generates an image of a QR Code .. I would like to automatically send that image to a folder on the server without the users had to choose the folder or location. Any idea how can I do this?
Thank you.
Daniel Medeiros
Hi,
Nice article, but I have one query.
Is there any limit in number of files, if I want to upload multiple files using FileReferenceList class?
Thanks
Anand Meena