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

Asked

Viewed 289 times

3

Well, I’m trying to validate max_size on 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 on hand, but do not know how to put together with the checkthis

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

uploadField.onchange = function() {
    if(this.files[0].size > 307200){
       alert("File is too big!");
       this.value = "";
    };
};
  • 1

    begins by modifying the file for photo in the variable uploadeField, and then you can paste your example normally into a tag script or document js. Tell me what happened.

  • Nothing has changed, it does not check the size to return the message "File is Too big"

  • shows how you made that change.

2 answers

1


Do so:

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

And you can rewrite the function that way, without having to resort to the event onchange all the time. And to remove the file, just assign vazio 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 type files[n].type, so you can better know what kind of file it is, and it can be done on both sides.

  • It worked, thank you very much Edilson!

  • 1

    @Felipesilva.

  • I don’t think I tested it right, the script is not working, it doesn’t accept any formatted, and I put the input and function exactly as you described. It always gives invalid format message

  • 1

    @Felipesilva because it is, there was an error there in the extension, I had suppressed the . and I didn’t put it back, I edited the answer. You can also put a . at the beginning of the extension: var extficheiro = '.' + ficheiro.value.split('.').pop(), you can also remove all points from var extensoes.

  • Edilson, thank you very much! The only thing that is not accepting at all is the format . zip, I do not know why... The rest is all ok, all formats configured working. Except the . zip, has some specific reason, theoretically if others are accepting, the . zip should also accept.

  • 1

    @Felipesilva in fact the verification condition should be much more pronounced, and instead of checking the extension, should check the type MIME, but so it gets simpler, so put the condition >= 0 because the .zip has an index 0 for being the first value of the array, do so: extensoes.indexOf(extficheiro) >= 0.

  • Thank you so much for the help, it was perfect! Congratulations, you know a lot!

Show 2 more comments

1

Inserts below your extension comparator:

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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.