4

In my asp.net web application, I have an asp.net image control in the master page. User can upload and change the image. However for some reasons the name of the image saved in server should remain the same. Generally this image should be cached in browser. When user try to change the image by uploading new image, the image file gets replaced in the server but user still sees the cached image in the browser. Is there anyway to refresh the image cached in the browser only at the time of saving the new image?

kaypee
  • 76
  • 1
  • 5

2 Answers2

8

One trick you could use to prevent caching is to concatenate a random string onto 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);
geedubb
  • 4,048
  • 4
  • 27
  • 38
  • 1
    requests with a query string will never cached by the browser. i would like this image to be cached, but at the time of changing the image the browser cache for this image should be refreshed forcefully.. using server side code or client side code.. – kaypee Nov 17 '13 at 17:45
  • In that case you could append the datetime that the source image file was last modified instead of the random number. – geedubb Nov 17 '13 at 22:23
  • Nice one. Thanks... :) – Kenzo_Gilead Jun 24 '17 at 10:52
4

One solution would be to use File.GetLastWriteTime to append to the image url.

You will get some performance hit for that but if your name has to stay the same and you want a real time update of the cache this would work for you:

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

Other solution would be to keep track of the image version in the database and whenever the user uploads a new image you change the version and append that to the url.

Davor Zlotrg
  • 6,020
  • 2
  • 33
  • 51