1
I have the following question, it is possible to limit on the client side with JS(or jquery) the size(kb) of the photo?
I would like to limit in 500kb at most using the input type="file"
<input type="file" name="imagem"/>
1
I have the following question, it is possible to limit on the client side with JS(or jquery) the size(kb) of the photo?
I would like to limit in 500kb at most using the input type="file"
<input type="file" name="imagem"/>
3
As an alternative to jQuery mode, it follows a way of doing 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" />
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) {
// ...
}
}
2 points. 1. it would be interesting to explain that using jQuery
2. It would be better to work with 1024 * x
because if(data.size > 500000) {
will give less than 500kb, 488kb broken
@Exact Marcelobonifazio. Kib = 1024 bytes. 500KiB = 512000 bytes.
Browser other questions tagged javascript html
You are not signed in. Login or sign up in order to post.
Cool works great, and how to clean the input when not allowed?
– Lennon S. Bueno
You can set the value of the element as empty: upload.value = ""; I will edit the code with this line...
– Lucas Caires