Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clear the image cache after editing an image on my site?

Tags:

c#

asp.net

I'm using an outside page to update an image in my system. When I'm redirected back to the page I've worked in, I still see the old picture. I don't see my changes until I press ctrl+f5. Is their any way to redirect with history delete or any other solution?

like image 512
Roy Amir Avatar asked Dec 21 '10 00:12

Roy Amir


People also ask

How do I clear the cache on my WordPress site?

To clear your WordPress site's cache with The WP Super Cache plugin, on your WordPress dashboard, navigate to Settings, then Wp Super Cache, then click Delete Cache.

What is images cache?

Cache files on an Android device are a collection of all of the images, videos, text files and more that are required to display things like web pages, advertisements and more.

Does browser automatically cache images?

Yes the browser will cache them, often even when your headers say otherwise.


2 Answers

Add a query string to your image source, it will prevent the browser from caching it. Some people use the date, I prefer the GUID

Guid g = Guid.NewGuid();
string GuidString = Convert.ToBase64String(g.ToByteArray());
GuidString = GuidString.Replace("=", "");
GuidString = GuidString.Replace("+", "");

Image1.ImageUrl = "/path/to/new/image.jpg?r=" + GuidString;

It will end up making your image source look similar to this:

 <img src="/path/to/image.jpg?r=Vqad3W8ZUG6oXgFzZIw" id="Image1" runat="server" />
like image 91
jon3laze Avatar answered Oct 01 '22 02:10

jon3laze


The decision to refresh or not is up to the browser. A standard technique for solving this is to add a timestamp to your images. For example:

<img src='/images/foo.jpg?ts=1'/>

When you update the image, send back:

<img src='/images/foo.jpg?ts=2'/>

The browser will see two different URL and request the image again. You can use a timestamp (last modified time of the file), a hash of the file contents, an incrementing integer, ... Anything to change the URL and force the browser to reload.

N.B. When serving static files, web servers will ignore the query string. So you don't need any code running to implement this. This technique also works well for any content that you want to force a refresh on including CSS, JS, ...

like image 20
James Kovacs Avatar answered Oct 01 '22 04:10

James Kovacs