Shkelqim Maxharraj Shkelqim Maxharraj - 4 months ago 11
HTML Question

Upload a photo in list

I'm making a list with a photos. And I'm using HTML5 and JS to upload a new photos in that list. And i have a issue here. Can anyone help me out in this.

This is my html

<form action="">
<input type="file" value="Add new image" id="addPhoto">
</form>

<ul class="list">
<li><img src="http://https://blog.shareaholic.com/wp-content/uploads/2015/06/shortlink.png" alt="" class="image"></li>
<li><img src="http://http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a" alt="" class="image"></li>
</ul>


And this is my JS

function changePhoto(input) {
if (input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var source = e.target.results;
$(".list").append("<li><img src="+source+"></li>")
}
reader.readAsDataURL(input.files[0]);
}}

$("#addPhoto").change(function()
changePhoto(this);
})


And Css

.image {
height: 100px;
width: 100px;
}


And this is the example https://jsfiddle.net/mwna2d7x/

Answer

You have two problems:

▶ You haven't loaded jQuery.

▶ There is no FileReader.results property.


In order to make this work:

▶ Add a recent version of jQuery.

▶ Change var source = e.target.results; to var source = e.target.result;


jsFiddle:here.

Snippet:

function changePhoto(input) {
  if (input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      var source = e.target.result;
      $(".list").append("<li><img src=" + source + "></li>")
    }
    reader.readAsDataURL(input.files[0]);
  }
}

$("#addPhoto").change(function() {
  changePhoto(this);
});
.image {
  height: 100px;
  width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<form action="">
  <input type="file" value="Add new image" id="addPhoto">
</form>
<ul class="list">
  <li><img src="https://blog.shareaholic.com/wp-content/uploads/2015/06/shortlink.png" alt="" class="image"></li>
  <li><img src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a" alt="" class="image"></li>
</ul>