开发者

How do I clear the image cache after editing an image on my site?

I'm using an outside page to update an image in my system. When I'm red开发者_C百科irected back to the page I've worked in, I still see the old picture. I don't see my changes until I press ctrl+f5. Is their any way to redirect with history delete or any other solution?


Add a query string to your image source, it will prevent the browser from caching it. Some people use the date, I prefer the GUID

Guid g = Guid.NewGuid();
string GuidString = Convert.ToBase64String(g.ToByteArray());
GuidString = GuidString.Replace("=", "");
GuidString = GuidString.Replace("+", "");

Image1.ImageUrl = "/path/to/new/image.jpg?r=" + GuidString;

It will end up making your image source look similar to this:

 <img src="/path/to/image.jpg?r=Vqad3W8ZUG6oXgFzZIw" id="Image1" runat="server" />


The decision to refresh or not is up to the browser. A standard technique for solving this is to add a timestamp to your images. For example:

<img src='/images/foo.jpg?ts=1'/>

When you update the image, send back:

<img src='/images/foo.jpg?ts=2'/>

The browser will see two different URL and request the image again. You can use a timestamp (last modified time of the file), a hash of the file contents, an incrementing integer, ... Anything to change the URL and force the browser to reload.

N.B. When serving static files, web servers will ignore the query string. So you don't need any code running to implement this. This technique also works well for any content that you want to force a refresh on including CSS, JS, ...


in C# there is a much simpler way. you set the bitmapimage CreateOptions to BitmapCreateOptions.IgnoreImageCache and it forces the image to load from file instead of using existing cache.

        var bi = new BitmapImage();

        StorageFile file = await StorageFile.GetFileFromPathAsync(filepath);
        const uint requestedSize = 400;
        const ThumbnailMode thumbnailMode = ThumbnailMode.PicturesView;
        const ThumbnailOptions thumbnailOptions = ThumbnailOptions.ResizeThumbnail;

        StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions);

        bi.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
        bi.DecodePixelHeight = 200;
        bi.DecodePixelWidth = 200;
        bi.SetSource(thumbnail);
        return bi;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜