Getting the size of a file in ColdFusion
Wednesday, February 13th, 2008Today I needed to get the size of a file I’m working with. If the file was being uploaded from an html form, I can get the file size after calling <cffile action="upload"> by looking to the cffile.fileSize variable. But in this case, my file was uploaded long ago.
It is possible to get the file size by using <cfdirectory action="list" directory="parentDir">. This will return a query containing entries for each file in the directory. One of the columns in the query will be the file size. You can narrow it down to returning only your file by specifying a filter.
<cfdirectory action="list" directory="parentDir" filter="myfile.txt">
I don’t know if this filter is applied before or after the directory contents are read in. Anyway I didn’t really like this approach, maybe I’m just spoiled by Ruby’s simplicity ( File.size(”myfile.txt”) ), but this seems like the round about way to get a file’s size.
There is a more elegant way to do it with Java, and its very simple. If we create a Java “file” object, we can call the length() method on that object to get the size of the file in bytes. You can do it in one line.
(more…)




