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

后端 未结 14 2180
囚心锁ツ
囚心锁ツ 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 01:49

    Append a query string with an arbitrary unique number (or time, or version number, etc.):

    <img src="image.png?80172489074" alt="a cool image" />
    

    This will result in a new request, because of the different URL.

    0 讨论(0)
  • 2020-11-29 01:49

    Append the current datetime to the image src:

    <img src="yourImage.png?v=<?php echo Date("Y.m.d.G.i.s")?>" />
    
    0 讨论(0)
  • 2020-11-29 01:49

    If you look at the data that is exchanged between your browser and the server, you'll see that the browser will send a HTTP HEAD request for the images. The result will contain the modification time (but not the actual image data). Make sure that this time changes if the image changes on the server and the browser should download the image again.

    0 讨论(0)
  • 2020-11-29 01:51

    in PHP you can use this trick

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

    The time() function show the current timestamp. Every page load is different. So this code deceive the browser: it read another path and it "think" that the image is changed since the user has visited the site the last time. And it has to re-download it, instead of use the cache one.

    0 讨论(0)
  • 2020-11-29 01:58

    It sounds like the concern is more about the primary user seeing their new image than cache being disabled entirely? If that's the case, you can do the following:

    var headers = new Headers()
    headers.append('pragma', 'no-cache')
    headers.append('cache-control', 'no-cache')
    
    var init = {
      method: 'GET',
      headers: headers,
      mode: 'no-cors',
      cache: 'no-cache',
    }
    
    fetch(new Request('path/to.file'), init)
    

    If you do this after a new image is uploaded, the browser should see those headers and make a call to the backend, skipping the cache. The new image is now in cache under that URL. The primary user will see the new image, but you still retain all the benefits of caching. Anyone else viewing this image will see updates in a day or so once their cache invalidates.

    If the concern was more about making sure all users see the most up to date version, you would want to use one of the other solutions.

    0 讨论(0)
  • 2020-11-29 01:59

    you can control the cache behaviour by playing with the HTTP headers.

    setting the expires header in past would force browser to not use cached version.

    Expires: Sat, 26 Jul 1997 05:00:00 GMT
    

    You can consult the RFC to have more details.

    0 讨论(0)
提交回复
热议问题