Updating images using a download file in ASP.MVC 4

I have 30 images, and next to them there is a button for uploading.

When you select a new image and click update, it should delete the old image and save the new image with the same name and path.

I do it with

string path = "~/Pics/Image1.jpg"; System.IO.File.Delete(Server.MapPath(path)); uploadfile.SaveAs(path); 

It works, I see a change in my folder, where I store all my images, but in the browser I see the old image, and I need to delete the cache in order to see the new image.

Is there a way to update my images and show new images without deleting the cache from the browser?

+4
source share
2 answers

This is a browser caching issue, as you suspect. What you can do is add a query string value or something in this direction so that the browser has to reload the file.

The end result will be image.jpg?image=randomNumber

I usually do this through javascript, and you can use generating-random-numbers-in-javascript-in-a-specific-range to help you figure it out.

Now, as a note, you add only the query string to the source of the image tag, just in case I was unclear.

+2
source

You need to modify the http-header Last-Modified in the browser to determine the image changes and upload a new image. Your answer is apparently correct.

 var headerValue = Request.Headers['If-Modified-Since']; if (headerValue != null) { var modifiedSince = DateTime.Parse(headerValue).ToLocalTime(); // Insert date of your file change if (modifiedSince >= dateOfFileChanged) { return new HttpStatusCodeResult(304, "Page has not been modified"); } } // page has been changed. // generate a view ... // .. and set last modified in the date format specified in the HTTP rfc. Response.AddHeader('Last-Modified', dateOfFileChanged. ToUniversalTime().ToString("R")); 

This code is extracted from this Last-Modified Header question in MVC .

+2
source

All Articles