ruk·si

jQuery
File Size

Updated at 2013-05-05 07:51

You can use ajax HEAD request to fetch file sizes from the server. This is not the most elegant approach but works if you do not have too many files that require file size fetching.

// Loop all links with class 'fetchSize'.
$('a.fetchSize').each(function() {
  var link = this;

  // Issue an AJAX HEAD request for each one
  $.ajax({
    type: 'HEAD',
    url: link.href,
    complete: function(xhr) {
      var size = humanize(xhr.getResponseHeader('Content-Length'));
      // Append the filesize to each
      $(link).append(' (' + type + ')');
    }
  });
});

function humanize(size) {
  var units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];

  // Order of Magnitude
  var ord = Math.floor( Math.log(size) / Math.log(1024) );
  ord = Math.min( Math.max(0, ord), units.length-1);

  var sizeText = Math.round( (size / Math.pow(1024, ord)) * 100 ) / 100;

  return sizeText + ' ' + units[ord];
}