上传列表中的照片

时间:2016-07-29 23:36:25

标签: javascript jquery html html5

我正在制作一张包含照片的列表,我正在使用HTML5和JavaScript在该列表中上传新照片,但我在此处有一个问题。任何人都可以帮助我吗?

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>

JavaScript的:

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);
});

CSS *:

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

演示: here

1 个答案:

答案 0 :(得分:2)

你有两个问题:

▶您尚未加载 jQuery

▶没有 FileReader.results 属性。

为了使这项工作:

▶添加最新版本的jQuery

▶将 var source = e.target.results; 更改为 var source = e.target.result;

jsFiddle:here

<强>段:

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>