Saturday, March 21, 2009

getFileSize

When you provide a link to a file for the user to download, it's sometimes nice to provide the size of the file so that they know what they're getting themselves into.


ASP

  1. function getFileSize(someFile)
  2.     dim fs
  3.     dim file
  4.     set fs = Server.CreateObject("Scripting.FileSystemObject")
  5.     set file = fs.GetFile(Server.MapPath(someFile))
  6.     getFileSize = FormatFileSize(file.size)
  7.     set file = nothing
  8.     set fs = nothing
  9. end function

The size property returns the size in bytes, which could be a very large number. As you may have guessed, we're going to write a FormatFileSize function to wrap around it.


ASP

  1. function FormatFileSize(size)
  2.     dim units
  3.     dim factor
  4.     units = Array("B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  5.     factor = log(size) \ 7
  6.     FormatFileSize = Round(size / (1024 ^ factor), 2) & units(factor)
  7. end function

I think it will be a very, very long time before we reach yottabytes, so this function should withstand the test of time. Next week I'll show you how to get the file type and why you might want that.


View ASP implementation on Snipplr

No comments: