输入类型文件,如何在屏幕上获取图像?

时间:2018-04-23 07:49:10

标签: javascript html

<input hidden type="file" id="inpfile" accept="image/*">

$('#inpfile').change(function(){
    var a = this.files[0];
    var reader = new FileReader();
    reader.readAsDataURL(a);
    reader.onload = function (e) {
        var imga = new Image();
        imga.src = e.target.result;
    }
});

那张照片在哪里? 我怎样才能真正在屏幕上显示并改变其风格?

1 个答案:

答案 0 :(得分:2)

执行new Image()时,只在内存中创建元素,而不是在DOM中。在DOM中创建元素<img>并使用它

$(document).ready(function(){
var currentIndex = 1;
$('#inpfile').change(function(){
    var reader = new FileReader();
    reader.readAsDataURL(this.files[0]);
    reader.onload = function (e) {
        $('<img id="img' + currentIndex + '" class="img">') // jQuery will create new element if you pass not CSS selector, but expression, like in this case. Element still in memory
        .attr('src', e.target.result) // Change src attribute of element to base64 encoded image source
        .appendTo('.gallery'); // Append previous created element to <div class="gallery"> in DOM
        currentIndex++; // Increment ID counter, so each element has unique ID
    }
});
});
.img {
  width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="inpfile" accept="image/*"/>
<div class="gallery"></div>