上传前的javascript预览图像

时间:2018-11-27 05:56:02

标签: javascript node.js

我依次在img框中输入了代码。但是,如果if(file.size> 1M)大,则img框中会出现空格。 如何获得下一个没有空格的图像?

**

  

上传前的javascript预览图像

**

<form class="my_form">
<input type="file" id="fileElem" multiple accept="image/*" 
onchange="handleFiles(this.files)">
<label class="button" for="fileElem">Select Images</label>
<div id="gallery">
<img id="**imgg0**" class="imgg">
<img id="**imgg1**" class="imgg">
<img id="**imgg2**" class="imgg">
<img id="**imgg3**" class="imgg">
<img id="**imgg4**" class="imgg">
</div>               
</form>
<script>
function handleFiles(files) {
var files = [...files]
var imgs = document.querySelectorAll('img');
files.forEach(function(file, index){
if(file.size > 1000000){
delete file[index];
} else{ 
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onloadend = function() {
var img = **document.getElementById('imgg'+index)**;
img.src = reader.result;  
}
} 
})
}
</script>
[enter image description here][1]


 [1]: https://i.stack.imgur.com/0dJ45.png

2 个答案:

答案 0 :(得分:0)

检查我的解决方案。

function handleFiles(files) {
    var imgs = document.querySelectorAll('img');
    //Image element undex
    let imgIndex=0;

    //Loop through all the images
    for(var i = 0; i < files.length; i++){
        var reader = new FileReader();

        reader.onload = function(e) {
          var img = document.getElementById('imgg'+imgIndex);
          img.src = e.target.result; 
          imgIndex++;
        }
        
        reader.readAsDataURL(files[i]);     
   }
}
<form class="my_form">
	<input type="file" id="fileElem" multiple accept="image/*" onchange="handleFiles(this.files)">
	<label class="button" for="fileElem">Select Images</label>
	<div id="gallery">
		<img id="imgg0" width="10%" class="imgg">
		<img id="imgg1" width="10%" class="imgg">
		<img id="imgg2" width="10%" class="imgg">
		<img id="imgg3" width="10%" class="imgg">
		<img id="imgg4" width="10%" class="imgg">
	</div>               
</form>

答案 1 :(得分:0)

用于多图像预览的简单解决方案。这会为文件控件中选择的图片动态创建img占位符

<div id="container01"></div>
<input id="filer" type="file" onchange="preview()" multiple="multiple" />

<script>
    function preview() {
        var element = document.getElementById("container01");
        for (var i = 0; i < event.target.files.length; i++) {
            var imgi = document.createElement('img'); // variable imgi has i loop counter   
            imgi.src = URL.createObjectURL(event.target.files[i]);
            imgi.style.width = "100px";
            imgi.style.height = "100px";
            element.appendChild(imgi); // add new preview to container

            var space = document.createTextNode(" "); // spacer between imgs
            element.appendChild(space); // add space for horizontal preview
//          var linebreak = document.createElement('br'); // add line break <br/>   
//          element.appendChild(linebreak);
            
            
        }
    }
</script>