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
  • 2,634
  • 6
  • 27
  • 51
  • the function that calls the src needs to be refreshed or called again on the client-side if the path stays the same and just the image is being replaced on the server-side. – Dhaval Jardosh Sep 09 '19 at 20:46
  • well, it is the callback of ajax and it calls every time when i upload new image. – umer Sep 09 '19 at 20:48
  • possible to show a working snippet, so we can take a look at it? – Dhaval Jardosh Sep 09 '19 at 20:49
  • If the file has the same path, it is being cached. Look at [this question](https://stackoverflow.com/questions/728616/disable-cache-for-some-images). – EternalHour Sep 09 '19 at 20:53

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,560
  • 2
  • 20
  • 27
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,489
  • 1
  • 10
  • 12