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>

5 Comments

  1. Roland Collins says:

    In CF8, we have GetFileInfo(path) to retrieve all of this information 🙂

  2. Ryan Stille says:

    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.

  3. John DeGrood says:

    the getFileInfo(path) function only works if you are dealing with a file on your one server, what if I need to see the size of a file on a remote server before I allow users to download the file – trying to control bandwidth issues.

  4. Helgi Hrafn Gunnarsson says:

    Leave it to ColdFusion to not have this basic functionality implemented until 2007. *sigh*

    Thanks for the tips. 🙂 It worked.

  5. JC says:

    I know this is a really old post, but in case someone else finds it, the answer to John DeGrood's question:
    <cfhttp method="head" url="http://wherever.com/whatever.jpg&quot; >
    <cfdump var="#cfhttp.Responseheader['Content-Length']#">

    I'd put the result into some kind of cached variable for some period of time, unless you expect the file on the remote server will change without changing filenames.