views:

189

answers:

5

i use such code

string.Format("<img src='{0}'><br>", u.Avatar);

u.Avatar-it's like '/img/path/pic.jpg'

but in this site i can upload new image instead old pic.jpg. so picture new, but name is old. and browser show OLD picture (cache). if i put random number like /img/path/pic.jpg?123 then works fine, but i need it only ufter upload, not always. how can i solve this?

A: 

Read your post again,,, sorry for general answer.

To workaround it do following On Application_Start create a Dictionary with uploaded images save it on Application object, set it to null. Once you upload an image add it to this Dictionary. Wrap every place avatars appear on your website with function that evaluates image in Dictionary if found return imagename.jpg?randomnumber and then delete it from a Dictionary else return just an imagename.jpg.

This is going to be heavy because you will need to check each image in Dictionary but this will do exactly what you need.

eugeneK
A: 

Append DateTime.Now.Ticks to the image url:

string imgUrl = 
    string.Format("<img src='{0}?{1}'><br>", u.Avatar,DateTime.Now.Ticks);

EDIT: I don' think this best practice are even a practice I would use. This is just a suggestion given the limited information given in case the Random implementation isn't truly Random.

rick schott
How is this different than the radnom number approach he already tried?
Manu
Plus, disabling caching is a bad idea. The site will perform a lot better with caching of the images.
Zan Lynx
Most Random implementation people use aren't Random. Its just a suggestion in case the Random implementation is the underlying issue.
rick schott
+5  A: 
string imgUrl = _
string.Format("<img src='{0}?{1}'><br>", _
u.Avatar, _
FunctionThatLookupFileSystemForItsLastModified(u.Avatar).Ticks.ToString());
mangokun
+1. Somehow include the last modification date in your url: this way you don't disable caching, but you still force reloading the image if it is changed/overwritten.
jeroenh
+2  A: 

Instead of linking to the images directly, consider setting up a generic HTTP handler to serve the images.

MSDN: HTTP Handlers and HTTP Modules Overview
Stack Overflow: How to use output caching on .ashx handler

Jon Seigel
A: 

You can set cache dependancy using the System.Web.Caching.CacheDependency namespace. This can set the dependancy on the file uploaded, and will release the cache for that file automatically when the file changes.

There are lots of articles and stuff on MSDN and other places so I will not go into details on all that level of detail.

You can do inserts, deletes and other management of cache using the tools available. (and this does not require you to change the file names or tack on stuff - it knows by the file system that the file changed)

Mark Schultheiss