Skip to content

Instantly share code, notes, and snippets.

@mojaray2k
Last active May 16, 2022 16:45
Show Gist options
  • Save mojaray2k/6619426 to your computer and use it in GitHub Desktop.
Save mojaray2k/6619426 to your computer and use it in GitHub Desktop.
Use jQuery to send a HEAD request with AJAX and get the size of a file without downloading it. This snippet places the size of the file in braces next to its name. The script issues a HEAD request, which only returns the headers and not the actual content of the file, which means that these requests are fast and lightweight.
// Loop all .fetchSize links
$('a.fetchSize').each(function() {
// Issue an AJAX HEAD request for each one
var link = this;
$.ajax({
type: 'HEAD',
url: link.href,
complete: function(xhr) {
var size = humanize(xhr.getResponseHeader('Content-Length'));
// Append the filesize to each
$(link).append(' (' + size + ')');
}
});
});
function humanize(size) {
var units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
var ord = Math.floor(Math.log(size) / Math.log(1024));
ord = Math.min(Math.max(0, ord), units.length - 1);
var s = Math.round((size / Math.pow(1024, ord)) * 100) / 100;
return s + ' ' + units[ord];
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Display files sizes next to download links</title>
</head>
<body>
<a href="001.html" class="fetchSize">First Trickshot</a>
<a href="034.html" class="fetchSize">This Trickshot</a>
<a href="ball.png" class="fetchSize">Ball.png</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="filessizes.js"></script>
</body>
</html>
@noctivityinc
Copy link

Does this work with CORS?

@chk7964
Copy link

chk7964 commented May 16, 2022

CORS in not working

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment