JavaScript selecting image to an img tag

html, image, image-uploading, javascript

Solution

You can try this by using file reader in javascript.

<div id="userphoto">
        <div class="gravatar-wrapper-128"><img id="image" src="body-img.jpg" alt="" class="logo" width="120" height="120"></div>
        <div class="change-picture-slide" style="top: 30px;">
            <input accept="image/*" type="file" id="upload" name="upload" onchange="readURL(this);"style="visibility: hidden;" />
            <a href="" onclick="changePicture(); return false">Change Picture</a>
        </div>
    </div>
    <script>
        function changePicture(){
            $('#upload').click();
        }
        function readURL(input)
        {
            if (input.files && input.files[0])
            {
                var reader = new FileReader();
                reader.onload = function (e)
                {
                    $('#image')
                    .attr('src',e.target.result);

                };
                reader.readAsDataURL(input.files[0]);
            }
        }



    </script>

Problem

I have a fake profile system for a class project, it requires a profile picture, and it needs an option to change it locally (from your hard drive). I have a working `img` tag that holds a placeholder image as a default, and when you click `change picture`, an open file dialog opens. All I need to work now is setting the image link for the `img` tag with the image they selected. This is what I have so far. ``` <div id="userphoto"> <a><div class="gravatar-wrapper-128"><img id="image" src="http://blog.ramboll.com/fehmarnbelt/wp-content/themes/ramboll2/images/profile-img.jpg" alt="" class="logo" width="120" height="120"></div></a> <div class="change-picture-slide" style="top: 30px;"> <input accept="image/*" type="file" id="upload" name="upload" style="visibility: hidden; width: 1px; height: 1px" /> <a href="" onclick="changePicture(); return false">Change Picture</a> </div> </div> <script> function changePicture() { //open the open file dialog document.getElementById('upload').click(); var link = document.getElementById('upload').url; //change picture var img = document.getElementById("image"); img.src = link; } </script> ``` Knowing this can not be done, how could I have the image the user selected be uploaded anonymously to imgur and using this link?

Original source

Related problems