Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (7k points)

Can anyone tell me how to make a simple image upload and display it on the page

I want this:

User will choose an image

The page will display the image without refreshing the page or going to another file.

There should be multiple <img src> because I wnat to display different image size.

This is my code:

<style>

    /* Image Designing Propoerties */

    .thumb {

        height: 75px;

        border: 1px solid #000;

        margin: 10px 5px 0 0;

    }

</style>

<script type="text/javascript">

    /* The uploader form */

    $(function () {

        $(":file").change(function () {

            if (this.files && this.files[0]) {

                var reader = new FileReader();

                reader.onload = imageIsLoaded;

                reader.readAsDataURL(this.files[0]);

            }

        });

    });

    function imageIsLoaded(e) {

        $('#myImg').attr('src', e.target.result);

        $('#yourImage').attr('src', e.target.result);

    };

</script>

<input type='file' />

</br><img id="myImg" src="#" alt="your image" height=200 width=100>

1 Answer

0 votes
by (13.1k points)
edited by

You can use URL.createObjetURL that creates a DOMString containing a URL representing the object given in the parameter

You can simply set the src of the image to that url:

window.addEventListener('load', function() {

  document.querySelector('input[type="file"]').addEventListener('change', function() {

      if (this.files && this.files[0]) {

          var img = document.querySelector('img');

          img.onload = () => {

              URL.revokeObjectURL(img.src);  // no longer needed, free memory

          }

          img.src = URL.createObjectURL(this.files[0]); // set src to blob url

      }

  });

});

In the body:

<input type='file' />

<br><img id="myImg" src="#">

Want to be a Full Stack developer? Check out the Full-Stack developer course from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...