ColdFusion Quickie - Moving a file to a day-based folder

This post is more than 2 years old.

Here is a quick ColdFusion tip I hope people find useful. Let's say you have a site where users upload files. You may store all these files in one main assets folder. Doing so though could lead to a very large folder, and after time could actually impact performance. What about creating dynamic folders based on the date? So if a user uploads a file today, it would be moved to assetroot/2009/6/10. Here is a quick example of that.

First, our code needs to determine what the folder name for the current date should be. Normally I would begin with an "assets" folder, but for this example, I'll consider the root folder to be the same folder as the CFM:

<cfset folder = getDirectoryFromPath(getCurrentTemplatePath())>

To create the date based folder, I'll use the format described above - year/month/day.

<cfset newFolder = folder & "/" & year(now()) & "/" & month(now()) & "/" & day(now())>

Remember from my Cross Operating System Guide that the forward slash works perfectly across all operating systems. No need to worry about \ versus /.

Now we need to see if this folder already exists. If multiple people are uploading files, you only need to create the folder once:

<cfif not directoryExists(newFolder)> <cfdirectory action="create" directory="#newFolder#"> </cfif>

What's nice is - even if the year folder, or month folder, doesn't exist, ColdFusion will create them for you. If the year and month folders exist, ColdFusion will just create the day folder.

Finally, you just need to move the file. If you were using cffile to process the upload, you could use the destination attribute. In my sample code, I just used a hard coded file.

<cfset fileToMove = expandPath("./missing.jpg")>

<cfset fileMove(fileToMove,newFolder & "/" & getFileFromPath(fileToMove))>

I pointed to a file in the same folder, missing.jpg, and used the fileMove function. Note how I get the file from the complete source path and use the newFolder attribute.

Here is the complete template (with a few additional outputs for testing):

<cfset folder = getDirectoryFromPath(getCurrentTemplatePath())>

<cfset newFolder = folder & "/" & year(now()) & "/" & month(now()) & "/p" & day(now())> <cfoutput>new folder is #newFolder#<br/></cfoutput>

<cfif not directoryExists(newFolder)> nope, doesn't exist<br/> <cfdirectory action="create" directory="#newFolder#"> </cfif>

<cfset fileToMove = expandPath("./missing.jpg")>

<cfset fileMove(fileToMove,newFolder & "/" & getFileFromPath(fileToMove))>

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for HERE Technologies. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA