Validate max_size in an input type="file" with JS

3

Well, I'm trying to validate max_size in js, but as I do not understand much, I was able to only validate accepted formats (jpg, png, etc ...)

<input type="file" name="photo" id="photo" onchange="checkfile(this);" />



function checkfile(sender) {
    var validExts = new Array(".zip", ".rar", ".pdf", ".jpeg", ".jpg", ".png", ".tif", ".gif", ".JPG");
    var fileExt = sender.value;
    fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
    if (validExts.indexOf(fileExt) < 0) {
      alert("Invalid file selected, valid files are of " +
               validExts.toString() + " types.");
      return false;
    }
    else return true;
}

I have an example in hands, but I do not know how to put it together with checkthis

var uploadField = document.getElementById("file");

uploadField.onchange = function() {
    if(this.files[0].size > 307200){
       alert("File is too big!");
       this.value = "";
    };
};
    
asked by anonymous 24.03.2017 / 03:10

2 answers

1

Do this:

<input type="file" name="photo" id="photo" onchange="verificar(this);" />

And you can rewrite the function in this way, without having to resort to onchange event at all times. And to remove the file, just assign vazio to the value of this field.

function verificar(ficheiro){
    var extensoes = [".zip", ".rar", ".pdf", ".jpeg", ".jpg", ".png", ".tif", ".gif"];
    var fnome = ficheiro.value;
    var extficheiro = fnome.substr(fnome.lastIndexOf('.'));
    if(extensoes.indexOf(extficheiro) >= 0){
        if(!(ficheiro.files[0].size > 307200)){
            alert('Pronto para carregar ficheiro');
            /* aqui, deve-se tambem validar o ficheiro no lado do servidor */
            return true;
        } else {
            alert('Ficheiro demasiado grande');
            // remover ficheiro
            ficheiro.value = "";
        }
    } else {
        alert('extensao inválida: ' + extficheiro);
        // remover ficheiro
        ficheiro.value = "";
    }
    return false;
}
  

Instead of verifying the file extension, it would be ideal to check the type files[n].type , so you can better know what kind of file it is, and this can be done from both sides.

    
26.03.2017 / 15:22
1

Insert below your comparator extension:

if (validExts.indexOf(fileExt) < 0) {
  alert("Invalid file selected, valid files are of " +
    validExts.toString() + " types.");
  return false;
}else if(sender.files[0].size > 307200){
  alert("File is too big!");
	this.value = "";
}
else return true;
    
24.03.2017 / 15:22