Hoyo
Hoyo

Reputation: 1074

Upload/Change image in Javascript/HTML

Basically, I'd like a feature just like twitter has like when we upload a picture on twitter then it automatically runs a spinner and change the image there on the old avatar place.

I tried to do this but kind of failed, however I did the following:

<script language="javascript">
    function changeImage() {


        document.getElementById("newavatar").src = "http://dummyimage.com/136x136/000/fff";

}
</script>


<img class="already-avatar" id="newavatar" src="avatar_default.png" width="136px" height="136px"/>
<input class="upload-image" onclick="changeImage()" type="file" name="avatar" accept="image/jpeg, image/png">

I'm doing the above, it actually changes the image however the image is not the selected one, I know the image needs to be uploaded first so it can change it but having hard time doing this.

Please help me if someone can, I'm a beginner, any help will be appreciated.

Thanks

Upvotes: 3

Views: 12853

Answers (3)

Gurminder Singh
Gurminder Singh

Reputation: 1755

try this:

<script language="javascript">
function changeImage() {
    document.getElementById("newavatar").src = document.getElementById("input-file").value;
}
</script>


<img class="already-avatar" id="newavatar" src="avatar_default.png" width="136px"    height="136px"/>
<input id="input-file" class="upload-image" onchange="changeImage()" type="file"    name="avatar" accept="image/jpeg, image/png">

you will have to change the event listener from "onclick" to "onchange" and the script also. Hope it helps!

Upvotes: 3

DGS
DGS

Reputation: 6025

The First thing you will need to do is either put the file input into a form and post synchronously to the server or use ajax to upload the file asynchronously. I recommend the former since ajax is probably a little tricky for a complete beginner.

The next step is handling the file once it has been submitted to the server. Depending on what language you are using to deal with server side requests the actual coding varies. But basically you want to arrange where your file is saved to when it is uploaded so that you know how to reference the file.

The last step is finding some way to tell the client where the new file is. You can utilize things like sessions and cookies for this or you can look into storing variables such as these in a database.

Upvotes: 1

tbraun89
tbraun89

Reputation: 2234

If I understand you right you first want to upload the image and then display it to the user without reloading the page.

Then you first have to upload it with PHP or an other language to your server using Ajax and then replace the image, therefore send the path of the image with the Ajax response and do the replace.

Here is an example how to do this.

Upvotes: 1

Related Questions