97

Does any one know how to do a simple image upload and display it on the page.

This is what I'm looking for.

  • User(me) will choose a image
  • The page will display the image without refreshing the page or going to another file.
  • Multiple <img src> will do because I need to display different image size.

This was my code. (Some of it are edited I got it from JSFiddle Playground)

/* 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);
};
/* Image Designing Propoerties */
.thumb {
  height: 75px;
  border: 1px solid #000;
  margin: 10px 5px 0 0;
}
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.1.js"></script>

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

7
  • Have you tried using a plugin/library for this? For instance, Dropzone. Commented Feb 28, 2014 at 5:35
  • No. I think I don't need it for now. Commented Feb 28, 2014 at 5:37
  • @aroth . Do you know what seems to be the problem with this code? Why my image isn't appearing? Commented Feb 28, 2014 at 5:48
  • 4
    The code throws errors as written. After cleaning it up it works just fine for me. See: jsfiddle.net/bPUkC/2. Also note that although this displays the image on the page, it is not actually uploading the image. Commented Feb 28, 2014 at 5:54
  • It looks good to see to work. But when I tried to copy and paste it on my editor, and tried to browse for it. It didn't work for me. :( Commented Feb 28, 2014 at 6:01

4 Answers 4

88

Here's a simple example with no jQuery. Use URL.createObjectURL, which

creates a DOMString containing a URL representing the object given in the parameter

Then, 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
      }
  });
});
<input type='file' />
<br><img id="myImg" src="#">

Sign up to request clarification or add additional context in comments.

2 Comments

Works with react also and really simple solution
It is better practice to attach the onload event listener before setting the source on the image.
13

A code snippet to preview the image you want to upload

<img id="output_image" height=50px width=50px\
<input type="file" accept="image/*" onchange="preview_image(event)">

<script type"text/javascript">
  function preview_image(event) {
    const reader = new FileReader(); //create a reader
    reader.onload = function(){ // set a handler what to do when done loading
      const output = document.getElementById('output_image'); // get the node
      output.src = reader.result; // set the result of the reader as the src of the node
    }
    reader.readAsDataURL(event.target.files[0]); // now start the reader
  }
</script>

1 Comment

Please add an explanation to your answer, why and how this code works. Code only answers are not very useful and can lead to cargo cult programming.
10

Try this, It supports multi file uploading,

$('#multi_file_upload').change(function(e) {
    var file_id = e.target.id;

    var file_name_arr = new Array();
    var process_path = site_url + 'public/uploads/';

    for (i = 0; i < $("#" + file_id).prop("files").length; i++) {

        var form_data = new FormData();
        var file_data = $("#" + file_id).prop("files")[i];
        form_data.append("file_name", file_data);

        if (check_multifile_logo($("#" + file_id).prop("files")[i]['name'])) {
            $.ajax({
                //url         :   site_url + "inc/upload_image.php?width=96&height=60&show_small=1",
                url: site_url + "inc/upload_contact_info.php",
                cache: false,
                contentType: false,
                processData: false,
                async: false,
                data: form_data,
                type: 'post',
                success: function(data) {
                    // display image
                }
            });
        } else {
            $("#" + html_div).html('');
            alert('We only accept JPG, JPEG, PNG, GIF and BMP files');
        }

    }
});

function check_multifile_logo(file) {
    var extension = file.substr((file.lastIndexOf('.') + 1))
    if (extension === 'jpg' || extension === 'jpeg' || extension === 'gif' || extension === 'png' || extension === 'bmp') {
        return true;
    } else {
        return false;
    }
}

Here #multi_file_upload is the ID of image upload field.

5 Comments

Thank you for this, but I need a Javascript code, not PHP.
I just need to display the image 4x on different sizes, I'm just having problems with my src but thank you for this. I'm gonna try this later. :D
You can return image from ajax call. In my example upload_contact_info.php. So you wll get image name in ajax response then you jest need to create dynamic image. That is it.
This is ridiculous but, I have no idea on how I can use your posted code. Haha! But I'll just work on it.
@HBKautil, where is the rest of the code? Where is the HTML part?
1
<li class="list-group-item active"><h5>Feaured Image</h5></li>
            <li class="list-group-item">
                <div class="input-group mb-3">
                    <div class="custom-file ">
                        <input type="file"  class="custom-file-input" name="thumbnail" id="thumbnail">
                        <label class="custom-file-label" for="thumbnail">Choose file</label>
                    </div>
                </div>
                <div class="img-thumbnail  text-center">
                    <img src="@if(isset($product)) {{asset('storage/'.$product->thumbnail)}} @else {{asset('images/no-thumbnail.jpeg')}} @endif" id="imgthumbnail" class="img-fluid" alt="">
                </div>
            </li>
<script>
$(function(){
$('#thumbnail').on('change', function() {
    var file = $(this).get(0).files;
    var reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.addEventListener("load", function(e) {
    var image = e.target.result;
$("#imgthumbnail").attr('src', image);
});
});
}
</script>

1 Comment

Please add explanation as to why your answer is more helpful than already existing answers. Also, try to avoid code-only answers in general.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.