1

I have an application in Asp.net Core MVC in which user upload his profile image. The server side is working fine but at client side when i change the image src for first upload, it works fine but after second time the image replaced at server but at client side it shows the same. That's how i am changing the src of an image.

var src = "/up_images/profiles/" + result.data;

 $("#profileImage").attr("src", src);

please note that i am replacing the existing image. In this case if src is "/up_images/profiles/137.jpg" then after uploading image the src will be the same. "137" is the user id.

if i refresh the page the image changes too.

also i have tried with some delay using timeout but it is not working. What is the issue?

Umer Waheed
  • 4,044
  • 7
  • 41
  • 62

2 Answers2

1

You can try appending a query parameter that changes for each request, onto the end of the URL. It will get ignored by the server side, but the browser will treat it as a new request and not re-use the cached image.

Something like this:

var src = "/up_images/profiles/" + result.data + "?v=" + Date.now();

 $("#profileImage").attr("src", src);
Nicholas Hirras
  • 2,592
  • 2
  • 21
  • 28
1

If the image path is exactly the same but resource changes, you'll want to force the request. That can easily be done by appending a query such as the current time.

$("#profileImage").attr("src", src + "?" + Date.now());

Or with template literals

$("#profileImage").attr("src", `${src}?${Date.now()}`);
Cue
  • 2,699
  • 1
  • 12
  • 13