json – Validar max_size em um input type=”file” com JS

Question:

Well, I'm trying to validate max_size in js, but since I don't understand much, I was only able to validate the 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 at hand, but I don't 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 = "";
    };
};

Answer:

Do like this:

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

And you can rewrite the function that way, without having to resort to the onchange event all the time. 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 checking the file extension, the ideal would be to check the files[n].type , so you can better know what kind of file it is, and this can be done from both sides.

Scroll to Top