JavaScript selecting image to an img tag

10,905

Solution 1

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>

Solution 2

Well, the native file uploading interface (as I've found) doesn't allow you to do that, assuming you're only working client-side.

The only time that <input type="file"/> will ever be useful to you is in a form that is submitted to a server because browser security measures prevent you from doing anything else with it.

Modern browsers will give you a fake file path on the client side as the result of a file upload to prevent malicious acts with the user's filesystem.

However, I think the Ink Filepicker API provides exactly the functionality you're looking for. When the user uploads a file, it will return an object that contains the name of the file and a URL that points to its download location, which is exactly what you're looking for (this would fill the src attribute of your image).

It's really simple to set up, actually.

First, sign up for a free account and grab an API key. In your head, set it up like this:

<script type="text/javascript" src="//api.filepicker.io/v1/filepicker.js"></script>
<script>filepicker.setKey('API_KEY');</script>

Then, you have access to all of the API's functionality.

To do what you're asking, you'll need to create a button like this:

<button onclick="handleFiles();">Upload Image</button>

Clicking on it will produce a dialog for the user to pick a file that looks like this:

enter image description here

Then, create a handler function:

<script>
    function handleFiles() {
        filepicker.pick({
            mimetypes: ['image/*'],
            //you can also define what uploading services you want to use here
        },
        function(e) { //you now have access to the file
            var link = e.url;
            //change picture
            var img = document.getElementById("image");
            img.src = link;            
        });
    }
</script>

I've found this to be a tremendously useful API: here are the docs.

Demo

Share:
10,905
Bryce Hahn
Author by

Bryce Hahn

Coding I kind of my thing. Even though I'm just starting out on Java and am fairly new to it, I never give up on an idea and keep at it until I resolve the problem.

Updated on June 22, 2022

Comments

  • Bryce Hahn
    Bryce Hahn almost 2 years

    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?

  • AstroCB
    AstroCB almost 10 years
    This will give you C:\fakepath\filename.extension because of the security implementations put into place by browsers.
  • Alexander O'Mara
    Alexander O'Mara almost 10 years
    Or just filename.extension.
  • Bryce Hahn
    Bryce Hahn almost 10 years
    So if for security reasons you can't do this... how about uploading this file to imgur.com or something like than anonymously and using that?
  • DrRoach
    DrRoach almost 10 years
    I would suggest using PHP's upload function as it seems the best tool for your job. Using different websites to host your user images just seems messy.
  • AstroCB
    AstroCB almost 10 years
    @DrRoach From the question, it sounds like a client-side-only option is required here.
  • Bryce Hahn
    Bryce Hahn almost 10 years
    @AstroCB yes, PHP is very useful but is not aloud within this project.
  • DrRoach
    DrRoach almost 10 years
    Okay so that makes more sense now, I would suggest then that you do infact try and get the absolute path to the image so that no files need to be moved, all you need to do is know where the file is currently stored. This is your only possible solution really as javascript can only operate in your browser. In short, get the path eg. 'C:/Users/user/Desktop/images/chosen_image.jpg' either via your file input or a text input and set this to your image source.
  • AstroCB
    AstroCB almost 10 years
    @DrRoach That's the problem; for security reasons, the real file path is obscured by the browser.
  • DrRoach
    DrRoach almost 10 years
    Oh really? Never knew that
  • AstroCB
    AstroCB almost 10 years
    @DrRoach Yes; you don't want to give a potentially malicious script access to your filesystem. stackoverflow.com/questions/4851595/…