- I upload a file using ajax (image to be exact).
- Saved the file in a certain location.
- I need the file name to be the saved as the single file name for each user, for example user1 should have an image of user1_pic.jpg.
- If I upload another image, it should replace user1_pic.jpg with the current uploaded image.
- Display the image back in the browser using ajax.
I don't want the page to refresh so I'm doing all in ajax. Now, when I upload a file say Image1.jpg then display it on the browser. The problem that I meet now is when I tried to display the newly uploaded image, the old image is the one displayed even though when I look at the physical file, it has already been changed.
The answer I found out is the previous image is being cached by ASP.NET MVC. If your request, any kind of page request, does not change in URL. ASP.NET MVC will give you the cached page instead of the original page.
My scenario is when I displayed the image, the image source URL is not changed, so ASP.NET MVC returns me the cached image URL instead of the original image URL. For example, my image URL is this. http://localhost/MySite/pictures/user1_pic.jpg. And this is requested several times by ajax request, even though my image is changed, ASP.NET MVC will still return the cached URL of the image. So I will see the old image instead of the newly uploaded image.
Solution:
The solution for this problem is so simple. I just need to change the image URL everytime I call an ajax request on success callback by adding a random parameter of the image. e.g. http://localhost/MySite/pictures/user1_pic.jpg?rand=3us9jl. The rand parameter value should always change since I am generating a random character on it.