Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh the browser cache of an image?

Tags:

c#

asp.net

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?

like image 484
kaypee Avatar asked Dec 16 '22 04:12

kaypee


2 Answers

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);
like image 187
geedubb Avatar answered Dec 30 '22 19:12

geedubb


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.

like image 29
Davor Zlotrg Avatar answered Dec 30 '22 20:12

Davor Zlotrg