Flex Examples
Detecting whether an image loaded successfully in Flex
The following example shows how you can listen for the httpStatus event on a Flex Image control to see if an image loaded successfully or not.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/11/04/detecting-whether-an-image-loaded-successfully-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import flash.events.HTTPStatusEvent;
private function img_httpStatus(evt:HTTPStatusEvent):void {
switch (evt.status) {
case 200:
// Valid image, do nothing.
break;
case 404:
// Invalid image, PANIC!
Alert.show("invalid image!", evt.status.toString());
break;
default:
Alert.show(evt.toString(), evt.status.toString());
break;
}
}
private function button_click(evt:MouseEvent):void {
img.source = textInput.text;
}
]]>
</mx:Script>
<mx:ApplicationControlBar dock="true">
<mx:HDividedBox width="100%">
<mx:TextInput id="textInput"
text="http://www.helpexamples.com/flash/images/image1.jpg" />
<mx:Button label="load image"
width="100"
minWidth="100"
maxWidth="100"
click="button_click(event);" />
<mx:Spacer width="100%" />
</mx:HDividedBox>
</mx:ApplicationControlBar>
<mx:Image id="img"
httpStatus="img_httpStatus(event);" />
</mx:Application>
View source is enabled in the following example.
Tagged with: httpStatus
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.
27 Responses to Detecting whether an image loaded successfully in Flex
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


I’m seeing ’0′ returned for both found and not found images.
Steve,
According to the documentation for the HTTPStatusEvent class’s status property (whew!), you may get a status code of 0 if Flash Player cannot get a status code from your server.
Peter
Pitty…
This was a really nice solution
Yep….switch over to IE and I’m no longer pulling the dialog box / status = 0. But doesn’t this bring us to browser-specific behavior? Isn’t madness just a little way down that road?
Doesnt work ! Server returns always 0 as status code ;-( If you want to check if your image has not been downloaded use , this code by instance change the image if img.source is not available.
Hope to help you
Hey Peter!
Thanks for the detailed description of status code 0. The documentation that came with flex 2.x does not mention it in as much detail. Is there any way around it so that I could stick to firefox as the development and deployment browser?
Cheers!
Harry S.
I concur Tom. Firefox and Safari return 0 always whereas IE works as expected.
Why am I using Flex? ;)
I am having a problem with loading images.
The problem is when I change the image (same name new image) on the server in flex it still look at the old image (same name old image) until I close the application and open it up then it shows the me image.
How can I get this to show the new image without reopening the application? The user needs to see the new image loaded.
Thanks
Chaz
it is because it get the image from the cache
try to add a random number after your file url :
http://www.helpexamples.com/flash/images/image10.jpg? + (Math.random() * 10000000);
but with this solution, it will always download the file from the server, even if the image has not changed…
Thank Petere for your illuminating examples.
I do have a smaller problem than the ’0′ being displayed that i need to tackle, I dont have an action script background but logic is a natural thing. I am trying to show an image from a node of a node of an xml list that populates a datagrid. what i want is to show the selected image. when i tried i loads just a broken link of the image. I must be missing something , any help here’s my code
private function doScan(evt:MouseEvent):void {
img.source = ‘resultGrid.selectedItem.imgpath’;
}
my xml file
2348056441978
BIOS ADMIN
Onne Field
26/04/2008
XN403ABr
../bin-debug/img1.jpg
2348034521561
BIOS ADMIN2
Sapele Deopt
26/04/2008
XN403ABw
../bin-debug/img2.jpg
With Mozilla the status cod is always 0. IE works perfectly. Is there any other way around with which we can find if the image loading is a success??? Is Flex browser specific???
Rahul,
Unfortunately, due to browser differences (ie: what the browser provides to the Flash Player), there can be subtle differences between browsers and OSes. In this case Firefox/Mozilla may not be passing the status code to the Flash Player plugin, but IE is passing the status codes to the ActiveX plugin.
Feel free to file a Flash Player bug at http://bugs.adobe.com/flashplayer/ and post the bug number here and a few of us can vote on the issue.
Peter
Hey Peter,
Not sure if we can file a Flash player bug as the problem might reside in the browser itself. Since, it works perfectly with IE. How to figure out the culprit here?
Is it Browser or the Flash Player..
Rahul
Rahul,
I would file the bug against Flash Player and if they determine the issue is with Firefox/Mozilla, they will either mark the bug as “External” and they may file a bug in the Mozilla bug base for you.
Peter
Hi, peterd. Can you also use this technique to see if the image loaded successfully?
try { myImage.load("myimage.jpg"); catch (ex:IOException) { // handle the error. }Probably not the best way according to OOP practices, though.
One caveat that I just discovered: On many browsers, the default HTTP status code of 0 is returned. From the LiveDocs for Flex 3 (http://livedocs.adobe.com/flex/3/langref/flash/events/HTTPStatusEvent.html):
If Flash Player or AIR cannot get a status code from the server, or if it cannot communicate with the server, the default value of 0 is passed to your code. A value of 0 can be generated in any player (for example, if a malformed URL is requested), and a value of 0 is always generated by the Flash Player plug-in when it is run in the following browsers, which do not pass HTTP status codes to the player: Netscape, Mozilla, Safari, Opera, and Internet Explorer for the Macintosh.
I’ve been testing on Firefox, which is a Mozilla browser. It’s returning 0 for the status always. Any workarounds for this?
Still no answer for detecting if an image is not loaded properly on other browsers??
Can’t believe I have to depend on users using Internet Explorer only!!!
Is ther a workaround?
I’ve found that the ioError Event is launched if there is a problem loading the image.
That’s enough for me to know that I need to change the image for a “Not available photo” image, and it work in Firefox, so I suppose it is not browser dependant.
Hope that helps someone with a similar problem.
I’m using
<mx:Image id="myImg" source="x" ioError="myImg.source = null"/>and it seems to work fine in both IE and FirefoxBrian – your solution seems to work for me across browsers. Thanks a lot.
Hi Peter,
How can I send a message to the user when the connection to the internet drops?
@Daniel,
You could try using a timer that runs every X seconds and does an HTTP get of a small file on your server. If the server connection fails, it is likely that the server or the internet connection is down and you could possibly display an alert/dialog.
Peter
Hi.,
I am using
iconField is using class name as menuIcon is url image file.. how to load url image file to icon field.,
Any one help me..
Ling’s
Hi.,
I am using mx:MenuBar id=”testmenu” labelField=”menuLabel” iconField=”menuIcon” dataProvider=”{Datamenu}” width=”100%” itemClick=”ClickMenuItem(event);” click=”Select_MenuBar(event);”
iconField is using class name as menuIcon is url image file.. how to load url image file to icon field.,
Any one help me..
Ling’s
Hi, i’m using this procedure to check if image loaded correctly, but I’m having problem on setting a default image when an error occurs. I would like to switch back to a default embedded image when server is returning other than 200 code.
Detecting if an image loaded successfully is as easy as 1.. 2.. 3.. 4……
This seems to be what is needed to get a reliable cross-browser load/fail for swfloader… what a PITA…
1. complete + init events. and compare bytes to make sure you have everything. See http://numiko.com/labs/?p=268
2. ioError
3. Wrap your .load call with a try/catch to make sure you get any security errors, and then fire the load fail event manually if you do.
4. Manual timeout. You need to write something that will track how long a load() has been active and timeout at some reasonable time for your app. You then need to cancel the SWFLoader so that it doesn’t eventually fire a complete/error down the road. Looks like SWFLoader.unloadAndStop can so this, though I’m not 100%.
Since swfloader doesn’t seem to have a timeout, it will wait as long as the remote server keeps your connection open and waiting (and your browser doesn’t kill it).
In theory, a web server could send one byte at a time and keep swfloader waiting indefinitely.
One example: In FF, I was contacting IIS for a site that has been stopped, it seems to take 1-2 minutes before the connection finally stops and flash hits an ioError event.
In the meantime, flash fires no events that I can see, ioError or otherwise. So for that entire time, your user will just be waiting, wondering what is going on.
For who is looking for an answer, test if the content is Bitmap, e.g.:
var image:Image;
//load image
…
trace(image.content is Bitmap); // true if its is loaded