Getting the size of a file in ColdFusion
Today 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.
<cfset fileSize = createObject("java","java.io.File").init("myfile.txt").length()>
Here it is in a reusable function:
<cffunction name="getFileSize">
<cfargument name="filepath">
<cfreturn createObject("java","java.io.File").init(Arguments.filepath).length()>
</cffunction>
February 14th, 2008 at 12:05 am
In CF8, we have GetFileInfo(path) to retrieve all of this information
February 14th, 2008 at 8:29 am
Doh! I had looked all over the docs too see if I was missing something, but I guess I just didn’t catch that. I have used ImageInfo(), which returns info about an image, so I was sure there would be a FileInfo(), too, but there wasn’t.
Anyway, good to know, thanks.