简体   繁体   中英

Find out if loaded image is not valid (e.g. is a 404 error page)

does someone know a way, how I could find out if a loaded image is not an image because eg a 404 error was returned?

In case of an error I would like to set my image URL to eg 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.

  1. Setup the bucket for static website hosting

  2. 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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM