Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Updating Images on Page

2.75/5 (3 votes)
5 Aug 2008CPOL1 min read 1  
This article will show you how to update an image control on a webpage, avoiding caching issues.

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:

VB
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)