How to update image browser cache?

In my asp.net web application, I have an asp.net control on the main page. User can upload and modify image. However, for some reason, the name of the image stored on the server must remain unchanged. Usually this image should be cached in the browser. When the user tries to change the image by uploading a new image, the image file is replaced on the server, but the user still sees the cached image in the browser. Is there a way to update the image cached in the browser only while saving a new image?

+4
source share
2 answers

One trick you can use to prevent caching is to concatenate a random line at the end of your image:

  <img src="/images/nocache.jpg?34343434" />

.aspx code

<asp:Image id="Image1" runat="server" />

Code behind:

    string baseImage = "/images/nocache.jpg";
    int rand = new Random().Next(99999999);
    Image1.ImageUrl = string.Concat(baseImage, '?', rand);
+6
source

One solution would be to use File.GetLastWriteTime to add an image to the URL.

You will get some performance gains, but if your name stays the same and you want to update the cache in real time, this will work for you:

string imageUrl = "/images/user.jpg";
imageUrl += "?ver=" + File.GetLastWriteTime(Server.MapPath(imageUrl)).ToFileTime(); 

Another solution would be to track the version of the image in the database and whenever the user uploads a new image, you change the version and add it to the URL.

+4
source

All Articles