【问题标题】:Multiple select in html file uploadhtml文件上传中的多项选择
【发布时间】:2021-09-20 21:04:12
【问题描述】:

我正在创建一个基本应用程序,允许用户上传图片,但我希望该用户最多上传 2 张图片。 所以任何想法,我应该如何做到这一点。

【问题讨论】:

    标签: html file-upload


    【解决方案1】:

    你需要在类型文件<input id="files" type="file" multiple> 的输入标签上使用多个属性
    这只解决了一半的问题,因为多个文件将允许任意数量的文件。

    您可以通过以下方式解决:

    • 向用户提供仅允许 2 个文件的信息。
    • 有时用户可能会在信息后选择超过2个文件,在这种情况下使用javascript报告错误
    <div class="wrapper">
      <label for="files">Upload Images
        <span>Maximum of only 2 files allowed
        </span>
      </label>
      <input type="file" id="files" multiple>
      <div id="error" class="error">
        Maximum of 2 files only can be uploaded
      </div>
    </div>
    <style>
    .wrapper {
      display: flex;
      justify-content: center;
      flex-direction: column;
    }
    .wrapper label {
      color: blue;
    }
    label > span {
      display: block;
      font-size: 10px;
    }
    .error {
       color: red;
       font-size: 20px;
       display: none;
     }
    </style>
    
    <script>
     files.addEventListener('change', (e) => {
      if(e.target.files.length > 2) {
        error.style.display = "block"
      } else {
        error.style.display = "none"
      }
    })
    </script>
    

    这里是codepen的链接https://codepen.io/shivakumarjakkani/pen/vYmXVxy

    【讨论】:

      【解决方案2】:

      您可以使用多个元素,例如:

        <input type="file" id="files" name="files" multiple><br><br>
      

      【讨论】:

        猜你喜欢
        • 2022-11-05
        • 1970-01-01
        • 2011-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-16
        • 1970-01-01
        相关资源
        最近更新 更多