Is there a way to force browsers to refresh/download images?

后端 未结 14 2181
囚心锁ツ
囚心锁ツ 2020-11-29 01:21

I have a problem where users are reporting that their images aren\'t being uploaded and the old ones are still there. On closer inspection the new images are there, they jus

相关标签:
14条回答
  • 2020-11-29 02:00

    that was not ok result, I think this is the way to program it correct.

     <td><?php echo "<img heigth=90 width=260 border=1 vspace=2 hspace=2 src=".$row['address']."?=".rand(1,999)."/>" ?></td>
    
    0 讨论(0)
  • 2020-11-29 02:01

    I had come up with this issue some times ago. And I was getting data through JSON in AJAX. So what I did is, I just added a Math.random() Javascript function and It worked like a charm. The backend I used was a flask.

    <img class="card-img-top w-100 d-block" style="padding:30px;height:400px" src="static/img/${data.image}?${Math.random()} ">

    0 讨论(0)
  • 2020-11-29 02:07

    It's tough. You really want images to be cached, but then you don't want to cache them once a new ones available:

    • Using expires header with a date in the past prevents any caching. Bad
    • Adding a "cache busting" parameter ?342038402 can fix the problem, but can also prevent the image ever from being cached, which is not what you want. Bad.
    • Using expires header with a short (lets say 1 hr) expires is better... after an hour the user will see the image, but your web server won't have to serve it every time. Compromise, but what time works? Not really feasible.

    The solution? I can think of two good options:

    • Look into eTags, and your ability to use them. These are designed for this situation. The browser will explicitly ask your server whether the file is up-to-date or not. You can just turn this on in apache if you don't have it aleady.
    • Create a new URL for each new image (and use a far-future expires header). This is what you are working on.
    0 讨论(0)
  • 2020-11-29 02:07

    Another powerfull solution:

    <img src="image.png?v=<?php echo filemtime("image.png"); ?>" />
    

    This print the "last-modification-timestamp" on the path.

    New version --> Download new image

    Same version --> Take cache's one

    0 讨论(0)
  • 2020-11-29 02:08

    You can put http-equiv in <meta> tag which will tell browser not to use cache (or even better -- use it in some defined way), but it is better to configure server to send proper http cache headers. Check out article on caching.

    Still, some browsers might not support all of http standard, but I believe it's the way to go.

    0 讨论(0)
  • In PHP you can send a random number or the current timestamp:

    <img src="image.jpg?<?=Date('U')?>">
    

    or

    <img src="image.jpg?<?=rand(1,32000)?>">
    
    0 讨论(0)
提交回复
热议问题