How to limit the size (kb) of a photo with JS?

1

I have the following question, can you limit the size (kb) of the photo on the client side with JS (or jquery)?

I'd like to limit by up to 500kb using input type="file"

<input type="file" name="imagem"/>
    
asked by anonymous 15.02.2017 / 16:36

2 answers

3

As an alternative to jQuery mode, there is a way to do it using pure Javascript (Vanilla). Remembering that the size is in bytes, that is: 1024 byte = 1 kbyte

var upload = document.getElementById("upload");
upload.addEventListener("change", function(e) {
    var size = upload.files[0].size;
    if(size < 1048576) { //1MB         
      alert('Permitido'); //Abaixo do permitido
    } else {           
      alert('Não permitido'); //Acima do limite
      upload.value = ""; //Limpa o campo          
    }
    e.preventDefault();
});
<input id="upload" type="file" />
    
15.02.2017 / 16:59
2

View this format with JQuery:

$('#inputFile').bind('change', function(e) {
  var data = e.originalEvent.target.files[0];
  // Exibe o tamanho no console
  console.log(data.size + "is my file's size");
  // Ou faz a validação
  if(data.size > 500 * 1024) {
    // ...
  }
}
    
15.02.2017 / 16:42