Thursday, September 22, 2011

A Trick to Deal With Image Cacheing

Let's paint a very common scenario. Suppose you have to upload images to a folder for your web application. You upload your image and it looks great. Then, suppose you have to upload an additional image, and you want to name it the same thing. The problem you'll inevitably face is that because of how browsers cache images, it's very likely that you see your old image again, even though you know for certain that it's been replaced by your new image in the folder. This can get quite frustrating!! Well, there's a very easy workaround to this. All of you have to do is append a random string to the imageUrl, and the browser will think of it as a different image, and not display the cached image. Here's an example, of an image I have displayed in a DataGrid:

protected void AdminGrid_OnRowDataBound(Object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.DataRow)
{

System.Web.UI.WebControls.Image imgPreview = (System.Web.UI.WebControls.Image)e.Row.FindControl("imgPreview");

Random rand = new Random();
imgPreview.ImageUrl = "../Images/Products/" + product.ImageName + "? rand=" + rand.Next().ToString();

}
}


I use the Random class to generate my random string which I append to my imageUrl, and now cacheing will never apply to this particular image. Easy peasy, lemon squeezy.

No comments:

Post a Comment