Introduction
This article will explain how to avoid caching issues when changing an image on an ASP.NET webpage.
Background
We had a page that allowed a user to upload a new picture for their bio. The current image was displayed on this page as well inside a standard <asp:Image />
control. The page also contained a <asp:FileUpload />
control for the user to update the image. The uploaded image would keep the same name as the previous image and simply overwrite the existing file.
Our problem was that when the user would update the image, the old image was still being displayed until either the user closed the browser or browsed a separate site altogether, thus clearing the cached version.
Using the code
The way to workaround this is really quite simple. All you really have to do is "trick" the browser into thinking that it is showing a new image. Below is how you accomplish this:
Image1.ImageUrl = "mypicture.jpg?s=" & DateTime.Now.Ticks.ToString()
All that is necessary is to add some unique value after the image name (i.e., query string). I chose Ticks
because it is mostly going to be unique. By doing this, you force the browser to retrieve the latest version of the image.
This is not a life altering posting, but I hope this helps someone.