How To Display File Sizes Next To Download Links Using Jquery And Ajax
Published on February 26, 2024 by Dinesh Uprety
Display file sizes next to download links using jQuery & Ajax
Ajax
AJAX is a fundamental building block for web apps. It allows you to send only the data that you need, saving bandwidth and speeding things up, making your sites feel native-like.
Did you know that you can send a HEAD request with AJAX and get the size of a file without downloading it? With jQuery this is very easy:
<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>
// 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];}
This code 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.
First Trickshot (871 bytes)This Trickshot (1.27 KB)Ball.png (12.49 KB)