多文件上传HTML/CSS/JS



我想在我的网站上的申请表中添加一个多文件上传按钮。到目前为止,我可以一次上传多个文件,并显示这些文件的列表。然而,我现在也想先上传一些文件并查看列表,然后我希望能够添加更多文件并保留该列表。然而,到目前为止,当我这样做时,已经上传的文件列表就会消失。这是HTML、CSS以及JS代码,我一直使用到现在。如果有人能告诉我如何在代码中更改这一点,我会很高兴。

如果我的问题有错,我很抱歉。这是我第一次使用stackerflow,英语不是我的第一语言。

谢谢你的帮助!:(

updateList = function() {
var input = document.getElementById('file');
var output = document.getElementById('fileList');
var children = "";
for (var i = 0; i < input.files.length; ++i) {
children +=  '<li>'+ input.files.item(i).name + '<span class="remove-list" onclick="return this.parentNode.remove()">X</span>' + '</li>'
}
output.innerHTML = children;
}
.custom-file {
position: relative;
font-family: helvetica;
overflow: hidden;
margin-bottom: 30px;
margin-top: 30px;
width: auto;
display: block;
padding: 10px;  
}
.custom-file-input{
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
cursor: pointer;
opacity: 0;
z-index: 100;
}
.custom-file img{
vertical-align: middle;
margin-right: 10px;
}
ul.file-list{
font-family: helvetica;
list-style: none;
padding: 0;
}
ul.file-list li{
padding: 5px;
}
.remove-list{
cursor: pointer;
margin-left: 10px;
}
<div class="custom-file">
<input type="file" class="custom-file-input" id="file" multiple onchange="javascript:updateList()" border=">
<label class="custom-file-label" for="file">
<img width="30" src="https://image.flaticon.com/icons/svg/54/54565.svg" /> Dateien auswählen</label>
</div>
<ul id="fileList" class="file-list"></ul>

不要直接更改输出的HTML,只需使用appendChild()将元素添加到末尾即可。

updateList = function() {
var input = document.getElementById('file');
var output = document.getElementById('fileList');
var li = document.createElement("li");
li.innerHTML = 
`${input.files[input.files.length - 1].name}
<span 
class="remove-list" 
onclick="return this.parentNode.remove()"
>X</span>`;
output.appendChild(li);
}
.custom-file {
position: relative;
font-family: helvetica;
overflow: hidden;
margin-bottom: 30px;
margin-top: 30px;
width: auto;
display: block;
padding: 10px;  
}
.custom-file-input{
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
cursor: pointer;
opacity: 0;
z-index: 100;
}
.custom-file img{
vertical-align: middle;
margin-right: 10px;
}
ul.file-list{
font-family: helvetica;
list-style: none;
padding: 0;
}
ul.file-list li{
padding: 5px;
}
.remove-list{
cursor: pointer;
margin-left: 10px;
}
<div class="custom-file">
<input 
type="file" 
class="custom-file-input" 
id="file" 
multiple 
onchange="javascript:updateList()" 
border=""
/>
<label class="custom-file-label" for="file">
<img 
width="30" 
src="https://image.flaticon.com/icons/svg/54/54565.svg" 
/> 
Dateien auswählen
</label>
</div>
<ul id="fileList" class="file-list"></ul>

最新更新