HTML:选择多个文件,但没有显示文件名? [英] HTML: select multiple files but no file names shown?

查看:339
本文介绍了HTML:选择多个文件,但没有显示文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用多个"标签让用户选择多个文件进行上传.

I am using "multiple" tag to let user choose multiple files for uploading.

<input type="file" name="files[]" multiple />

但是它仅显示例如选择了3个文件".最好还显示文件名.

But it only shows e.g., "3 files selected". It would be better to also show file names.

这可行吗?谢谢.

顺便说一句,在这种情况下,如何取消选择文件(例如清除列表)?

BTW, in this case how to deselect files (e.g., clear the list)?

推荐答案

您可以使用输入元素上的.files属性来做到这一点:

You can do this with the .files property on the input element:

document.getElementById('files').addEventListener('change', function(e) {
  var list = document.getElementById('filelist');
  list.innerHTML = '';
  for (var i = 0; i < this.files.length; i++) {
    list.innerHTML += (i + 1) + '. ' + this.files[i].name + '\n';
  }
  if (list.innerHTML == '') list.style.display = 'none';
  else list.style.display = 'block';
});

<input type="file" id="files" multiple />
<pre id="filelist" style="display:none;"></pre>

如果上一个选择中还有其他内容,它将首先清空列表,然后遍历文件列表中的每个项目,然后将其添加到输入下方的<pre>元素中.如果列表中没有选定的项目,则<pre>将被隐藏.

This first empties the list in case there's still something from the previous selection, and then it goes through each item in the file list, and then adds that to the <pre> element underneath the input. The <pre> will be hidden if there are no selected items in the list.

PS:您可以通过单击输入,然后按 esc 或在文件选择窗口中单击取消"来清除列表.

PS: you can clear the list by just clicking the input, and then either pressing esc or clicking "cancel" on the file-selection window.

这篇关于HTML:选择多个文件,但没有显示文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆