<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>含样式的文件选择器</title>
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Ma+Shan+Zheng&display=swap" rel="stylesheet">  
  <style>
    body {
      font-family: 'Ma Shan Zheng', sans-serif;
      margin: 20px auto;
      max-width: 400px;
    }

    form > div {
      margin-bottom: 20px;
    }

    button, label, input {
      display: block;
      font-family: inherit;
      font-size: 100%;
      padding: 0;
      margin: 0;
      box-sizing: border-box;
      width: 100%;
      padding: 5px;
      height: 30px;
    }

    input[type="file"] {
      height: 0;
      padding: 0;
      opacity: 0;
    }

    label[for="file"] {
      box-shadow: 1px 1px 3px #ccc;
      background: linear-gradient(to bottom, #eee, #ccc);
      border: 1px solid rgb(169, 169, 169);
      border-radius: 5px;
      text-align: center;
      line-height: 1.5;
    }

    label[for="file"]:hover {
      background: linear-gradient(to bottom, #fff, #ddd);
    }

    label[for="file"]:active {
      box-shadow: inset 1px 1px 3px #ccc;
    }

    button {
      width: 60%;
      margin: 0 auto;
    }
  </style>
</head>

<body>
  <form>
    <div>
      <label for="file">选择要上传的文件</label>
      <input id="file" name="file" type="file" multiple>
      <ul id="file-list">

      </ul>
    </div>
    <div><button>提交</button></div>
  </form>

  <script>
    const fileInput = document.querySelector('#file');
    const fileList = document.querySelector('#file-list');

    fileInput.addEventListener('change', updateFileList);

    function updateFileList() {
      while(fileList.firstChild) {
        fileList.removeChild(fileList.firstChild);
      }

      let curFiles = fileInput.files;

      if(!(curFiles.length === 0))  {
        console.log('test');
        for(let i = 0; i < curFiles.length; i++) {
          const listItem = document.createElement('li');
          listItem.textContent = '文件名：' + curFiles[i].name + '；文件尺寸 ' + returnFileSize(curFiles[i].size) + '。';
          fileList.appendChild(listItem);
        }
      }
    }

    function returnFileSize(number) {
      if(number < 1024) {
        return number + 'bytes';
      } else if(number >= 1024 && number < 1048576) {
        return (number/1024).toFixed(1) + 'KB';
      } else if(number >= 1048576) {
        return (number/1048576).toFixed(1) + 'MB';
      }
    }
  </script>
</body>

</html>
