Skip to content

Instantly share code, notes, and snippets.

@brcontainer
Last active March 27, 2019 17:43
Show Gist options
  • Save brcontainer/b68ca1a9e850f9c1962defa424986759 to your computer and use it in GitHub Desktop.
Save brcontainer/b68ca1a9e850f9c1962defa424986759 to your computer and use it in GitHub Desktop.
Async get file size
function getImageSizeInBytes(imgURL, done, fail)
{
var request = new XMLHttpRequest;
request.open("HEAD", imgURL, true);
request.onreadystatechange = function () {
//Se ainda não for o 4 ignora com return
if (request.readyState != 4) return;
//Se a resposta não estiver no range do 200 a 299 (códigos de sucesso no HTTP usam o 2xx) deve develver um caballck de erro
if (request.status < 200 || request.status >= 300) {
fail(request.status);
return;
}
var headerText = request.getAllResponseHeaders(),
parse = headerText.match(/\bcontent-length:(\s)?(\d+)\b/i);
if (parse) {
done(parseInt(parse[2]));
} else {
fail('tamanho não definido');
}
};
request.send(null);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment