What is the best way to force an image refresh on a webpage?

26,568

Solution 1

This is a trick, but it works.

Put a variable and random number in the image url. Something like:

<img src="photo.jpg?xxx=987878787">

Maybe there's a better way, but it works for me.

Solution 2

Expanding on one of the other answers

if you have the photo on your server, or accessible then you can stat the file itself and use the modified time in the image source:

<?php

    if (is_file($PathToFile . '/photo.jpg'))
    {
       $FileDetails = stat($PathToFile . '/photo.jpg');
       echo '<img src="photo.jpg?MT=' . dechex($FileDetails['mtime']) . '" />';
    }

?>

This gives the best of both worlds as it will use browser caching normally but will force a re-read if the image file is changed (e.g. through re-upload)

Share:
26,568
leora
Author by

leora

Updated on November 25, 2020

Comments

  • leora
    leora over 3 years

    I have a an asp.net-mvc site. On one of the pages, I have an image, I use jcrop to allow users to crop the image. When this click submit, I crop the image on the server side and then reload the page. The issue is that the image looks the same as before . . if i hit F5 and refresh the page then the updated image shows up..

    Is there anyway to avoid having to force a F5 refresh in this case?