【问题标题】:javascript validation for multiple file upload before being uploaded in html在以 html 上传之前对多个文件上传进行 javascript 验证
【发布时间】:2021-11-11 12:08:31
【问题描述】:

我想验证我上传的多个文件不超过 2MG 所以我只需要一个 javascript 代码来处理这种情况

<input type="file" id="file" multiple>

【问题讨论】:

标签: javascript html file-upload


【解决方案1】:

post that i recommended 给你答案,编程不只是 ctrl+c 和 ctrl+v

document.getElementById("fileinput").addEventListener("change", function showFileSize() {
    // (Can't use `typeof FileReader === "function"` because apparently it
    // comes back as "object" on some browsers. So just see if it's there
    // at all.)
    if (!window.FileReader) { // This is VERY unlikely, browser support is near-universal
        console.log("The file API isn't supported on this browser yet.");
        return;
    }
    const maxAllowedSize = 2 * 1024 * 1024;
    var input = document.getElementById('fileinput');
    if (!input.files) { // This is VERY unlikely, browser support is near-universal
        console.error("This browser doesn't seem to support the `files` property of file inputs.");
    } else if (!input.files[0]) {
        addPara("Please select a file before clicking 'Load'");
    } else {
       Array.from(input.files).forEach(file => {
        if(file.size > maxAllowedSize) {
          addPara(file.name + ": error");
        }else {
          addPara(file.name + ": success");
        } 
       });
    }
});

function addPara(text) {
    var p = document.createElement("p");
    p.textContent = text;
    document.body.appendChild(p);
}
body {
    font-family: sans-serif;
}
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput' multiple="multiple">
</form>

【讨论】:

    【解决方案2】:

    答案来自:This solution

    const input = document.getElementById('input')
    const textDemo = document.getElementById('demo')
    
    input.addEventListener('change', (event) => {
      const target = event.target
      if (target.files && target.files[0]) {
    
        /*Maximum allowed size in bytes
          5MB Example
          Change first operand(multiplier) for your needs*/
        const maxAllowedSize = 5 * 1024 * 1024;
        textDemo.innerHTML = "Within 5MB limit"
        if (target.files[0].size > maxAllowedSize) {
          // Here you can ask your users to load correct file
          target.value = ''
          textDemo.innerHTML = "Exceeds 5MB limit"
        }
      }
    })
    <input type="file" id="input" />
    <div id="demo"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-03
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-04
      • 2015-04-22
      相关资源
      最近更新 更多