How to stop the browser from caching images

I came across this issue when building an “image manager”. The user would be prompted to upload an image, I would save it and change it’s name to a meaningful code. Problem is that when the page refreshed, the old image still showed. This was due to browser caching.

The browser uses caching so that you don’t have to download the same image multiple times. It recognizes an image by the url, so in order to stop caching we need to change the url so that the browser recognizes it as a new image.

C# Code:


// Add a meaningless but UNIQUE query string parameter to the url to stop browser caching the image
imgThumb.ImageUrl = String.Format("{0}?{1}", imageUrl, DateTime.Now.ToFileTimeUtc());

Please note that the following example is using C# server-side code to manipulate an ASP.NET <asp:Image> control . You could implement the same principle on a <img> tag’s “src” attribute using JavaScript.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s