does someone know a way, how I could find out if a loaded im开发者_如何转开发age is not an image because e.g. a 404 error was returned?
In case of an error I would like to set my image URL to e.g. white image.
I can't use server-side techniques like 404-error-handling or servlets, because I want to serve my images with Amazon S3 which doesn't have error handling or redirecting to a "default file" in case the requested image was not found.
The Image
class has an addErrorHandler
method. Register an error handler, which is fired in case the image was not loaded correctly. In this handler you can than set the image to a default image.
You may find the answer to this question useful. It uses jQuery but the idea of detecting that an image was not correctly loaded in the browser is well handled.
Not sure what the state of error handling was when this question was asked but S3 currently has 404 error handling. I use that to generate thumbs on demand.
Setup the bucket for static website hosting
Add a redirection rule under the static website hosting section such as:
<RoutingRules> <RoutingRule> <Condition> <KeyPrefixEquals/> <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals> </Condition> <Redirect> <HostName>yoursite.com</HostName> <ReplaceKeyPrefixWith>image/generate/</ReplaceKeyPrefixWith> </Redirect> </RoutingRule> </RoutingRules>
In the above case a missing image (i.e. cat.jpg) will cause a call to:
http://yoursite.com/image/generate/cat.jpg
In my case I use that to deliver thumbnails.
Here's a use case:
<img src="http://awsbucketurl.com/thumb_cat.jpg">
This causes a 404 triggered by S3 which then calls my site with the url. I see that it is prefixed with 'thumb_' and will then fetch cat.jpg from S3, resize, upload thumb to S3 for next time and deliver it as well to browser for this session.
One caveat: If the image is called by a caching system then it will not receive the new image after the 404 but instead store the missing image.
精彩评论