10

I am making a web application with MVC4 and C#.

I am allowing the user to upload an image for their profile picture. At this moment, I need the previous profile picture to expire so that when the browser reloads the page the new image is displayed. Currently, since both of the images share the same name the browser uses the previous image that has been cached instead of the new image.

If I force the browser to reload with F5 it shows the new image. How do I make sure that a user returning to their profile page sees the new image and not the one in the browser cache without hitting F5?

1
  • 5
    How about changing name? + google for If-Modified-Since
    – zerkms
    Commented Nov 13, 2012 at 21:47

2 Answers 2

7

You can add a dummy parameter to the end of the image filename. For instance,

<img src="...\avatar.jpg?d=7615833">

where the number is random or a timestamp. It will be ignored, but the presence will force the browser to reload the image.

4
  • Why not use no-cache then? Random parameter is just ugly
    – zerkms
    Commented Nov 13, 2012 at 22:01
  • Wouldn't he have to add the same number every time if he wants to prevent the image reloading?
    – neeKo
    Commented Nov 13, 2012 at 22:01
  • 3
    Perhaps use the changed-date of the file or a hash of its contents. Commented Nov 13, 2012 at 22:02
  • No-cache is the 'correct' way, but I've found browsers to be very stubborn in their refusal to cache/not cache according to instructions. The tag on the image url is quick and dirty, but workable. Niko is right, a random number would force a reload every time it's displayed; something reproducible is better, like the file creation time, or a simple version counter. Commented Nov 13, 2012 at 22:42
2

When storing the image on the server, add a (static) bit of random text to the file name, and re-generate it when the image changes. That way, the browser will cache the image when it is the same and reload it when it changes, which gives the desired behavior without adding unnecessary page load time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.