0

I want to validate that the multiple files that i upload to not exceed 2MG so i just need a javascript code to handle that situation

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

mr Ahmed
  • 3
  • 1

2 Answers2

0

the post that i recommended for you had the answer, programming is not just ctrl+c and 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>
naxsi
  • 602
  • 3
  • 15
0

Answer from : 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>
Rana
  • 2,500
  • 2
  • 7
  • 28