0

I am working on an application which will serve some image to the client, and sometime the image may be blank, and we use spring mvc as the controller, this is the core codes:

@RequestMapping
public ResponseEntity<byte[]> getImg(String id) {
    byte[] res = imgService.find(id); // this res  may be null
    headers.setDate("Expires", System.currentTimeMillis() + 24 * 3600 * 1000 * 7);
    return ResponseEntity.ok().headers(headers).contentType(MediaType.IMAGE_PNG).body(res);
}

As shown, the response code will always be 200 no matter the image exist or not.

And in the client side after I load the image , I will add the onerror event for the image, however I found that the onerror event will be triggered once the server can not find the image(which means the body may be null) even the status code is 200.

Then I tried to return a fixed image once the required image is missing, and the onerro event is not triggered.

So I wonder how does the browser think a certain img load error, it seems that it is not based on the status code.

Any documents about this?

hguser
  • 35,079
  • 54
  • 159
  • 293
  • Are you sure that byte[] res = imgService.find(id); res return your image, or just in your comment it will be null. So in your question " image(which means the body may be null) even the status code is 200." So it means you should check that if data is null you should add onerror, 200 status means there is no error occurred at http protocol. – erhun Apr 29 '15 at 08:37

1 Answers1

0

Adding event listner on the Img tag and have your custom logic called.

Sample code:

<img id="photo"
     onload='loaded(this.id)'
     src=""
     alt="alt text"
     />

There is post on how to detect the image load errors. Post 1, detecting using plain Javascript and also this.

Community
  • 1
  • 1
Vishnu
  • 1,011
  • 14
  • 31