In my project, people can include a personal photo so they can be easily identified.
What I am doing at the moment is the following:
- Monitor the
input
with typefile
that I have so that, when it changes value, the action of saving said photograph is executed. - I use the function
$.ajax()
to send the file to the server and from there it is processed. - The server returns the
path
where the photo was stored so you can replace the value of myimg
where it should be displayed.
Now in a little more detail:
Everything in numeral 1 and 2 works fine. Then, for number 3, I have the following. In my php file I move the file and give a response with the following code (simplified for obvious reasons):
move_uploaded_file($_FILES['usuariofoto']['tmp_name'],$directorio.$nombre_img);
$full_path = $directorio.$nombre_img;
$response = array(1,$full_path);
echo json_encode($response);
I understand that, if not specified otherwise, it move_uploaded_file
overwrites the file, which is good, since I don't want to have a bunch of photos for the same person. ( $nombre_img
it is a unique id for each person and $directorio
it is the name of the folder)
Back in JQuery, I'm trying to update the img with
var response = JSON.parse(postresult);
$("#usuariovistafoto").attr("src", response[1]);
So far so good, but the image does not change. When I inspect the element img
, I see that it has the same name as always, but this is normal, since I am overwriting the photo. I refresh the page manually and, indeed, if the photograph has been saved correctly, the new photo I have uploaded is displayed.
So, here is the problem. I suppose that since the file has the same name, the image is not updated and you still see the same photograph, although, in effect, all the changes have been carried out.
What do I have to do so that, so to speak, my img
"render" again even though it has the same file name in the src
?
That happens because the image will be in the cache.
You could add a
?ver=1234
at the end, example:This way you avoid that the image with the same name is cached at the moment of receiving it.
This example with ajax, the loadImagenesAll() function generates the rows of a table with the necessary images and after calling the editImagen() function I only call loadImagenesAll() again to render the images, it is worth mentioning that I have the images in a longblob field in the db, I hope it works for you.