如何在 JS 中上传图片并查看文件的预览?
2022-03-03
57
我正在尝试上传图片,并且该图片有预览。问题是当我上传图片时,我收到以下错误:
Uncaught TypeError: cannot set property ‘innerHTML’ of null
如果我删除以下行:
imageContainer.innerHTML="";
屏幕上会显示以下内容:
1 console.log({numOfFiles}); Files Selected
我想要的是显示图片,我做错了什么?我正在按照教程操作,教程中对他有用,但对我却没用
HTML
<div class="container">
<input type="file" name="fotosCarro" class="form-control" multiple="" id="file-input" onchange="preview()" accept="image/*" required="">
<label for="file-input">Upload images</label>
<p id="num-of-files">No files chosen</p>
<div class="images"></div>
</div>
CSS
input[type="file"]{
display:none;
}
.upload-label{
display:block;
position:relative;
background-color:#025bee;
color:#fff;
font-size:18px;
text-align:center;
width:300px;
padding:18px 0;
margin:auto;
border-radius:5px;
cursor:pointer;
}
#images{
width:90%;
border:1px solid black;
position:relative;
margin:auto;
display:flex;
justify-content:space-evenly;
gap:20px;
flex-wrap:wrap;
}
figure{
width:45%;
}
figcaption{
text-align:center;
font-size:2.4vmin;
margin-top:0.5vmin;
}
JS
let fileInput=document.getElementById("file-input");
let imageContainer=document.getElementById("images");
let numOfFiles=document.getElementById("num-of-files");
function preview(){
imageContainer.innerHTML="";
console.log({imageContainer});
numOfFiles.textContent=`${fileInput.files.length}
console.log({numOfFiles});
Files Selected`;
for(i of fileInput.files){
let reader=new FileReader();
console.log({reader});
let figure=document.createElement("figure");
console.log({figure});
let figCap=document.createElement("figcaption");
console.log({figCap});
figCap.innerText=i.name;
figure.appendChild(figCap);
reader.onload=()=>{
let img=document.createElement("img");
img.setAttribute("src",reader.result);
figure.insertBefore(img,figCap);
}
imageContainer.appendChild(figure);
reader.readAsDataURL(i);
}
}
1个回答
确保在要使用的元素后为 JavaScript 代码添加脚本标记,否则
document.getElementById(...)
将找不到它们
此外,最后一个 div 应该有
id="images"
而不是 class
xxMrPHDxx
2022-03-03