facebook google plus twitter
Webucator's Free ColdFusion MX Tutorial

Lesson: Working with Files and Directories

Welcome to our free ColdFusion MX tutorial. This tutorial is based on Webucator's Comprehensive ColdFusion Training course.

Lesson Goals

  • To work with <cffile> to read from and write to files.
  • To upload new files to the server.
  • To work with ColdFusion's file functions.
  • To work with <cfdirectory> to list the contents of a directory.
  • To work with ColdFusion's directory functions.

Using <cffile>

The <cffile> tag is used for working with files. The action attribute of <cffile> dictates what action will be performed on the file in question. The table below describes the different actions that can be performed.

<cffile> Actions
Action Description
read Reads a text file on the server into a local variable.
read binary Reads a binary file on the server into a local variable.
write Writes a text file to the server.
append Appends text to a text file on the server.
move Moves a file on the server from one directory to another.
rename Renames (or moves) a file on the server.
copy Copies a file on the server.
delete Deletes a file from the server.
upload Saves a file to a directory the server.

Reading from a File

When reading from a file, <cffile> requires three attributes:

<cffile> Attributes for Reading Files
Attribute Description
action Must be set to read.
file The absolute path to the file to be read.
variable The variable to hold the contents of the file.

In this lesson, we will be working with FilesAndDirs/Logs/RunningLog.txt, which is a tab-delimited text file. Each line is formatted as follows:

FirstName#chr(9)#LastName#chr(9)#time#chr(9)#comments#chr(10)##ch r(13)#

The file is divided into "columns" using tabs (chr(9)) and rows using hard returns (chr(10)chr(13)). The file is shown below.

Code Sample:

FilesAndDirs/Demos/Logs/RunningLog.txt
11/10/07	3 miles	26:34	Man, am I out of shape
11/12/07	3.1 miles	28:23	I'm still sore from last time
11/24/07	2.5 miles	23:44	It's like I haven't run for two weeks
12/24/07	4.1 miles	34:02	I'll be in shape by Christmas!

The code below reads and displays the file in the browser.

Code Sample:

FilesAndDirs/Demos/RunningLog.cfm
<html>
<head>
  <title>Running Log</title>
</head>
<body>
<h1>Running Log</h1>
<a href="AddEntry.cfm">Add Entry</a><hr/>
<cfset RunningLogPath = ExpandPath("Logs/RunningLog.txt")>
<cfset CrLf = chr(10) & chr(13)>
<cfif FileExists(RunningLogPath)>
	<cffile action="read" file="#RunningLogPath#" variable="myfile">
	<cfloop list="#myfile#" index="run" delimiters="#CrLf#">
		<cfoutput>#run#<br/></cfoutput>
	</cfloop>
<cfelse>
	You have apparently never been running.
</cfif>
</body>
</html>

Let's look at the ColdFusion code step by step.

First, we create a variable that holds the absolute path to RunningLog.txt. Remember, the file attribute of <cffile> requires an absolute path to the file.

<cfset RunningLogPath = ExpandPath("Logs/RunningLog.txt")>

Next, we create a variable called CrLf that holds a carriage return/line feed. We'll use this as the delimiter when we loop through the lines in the file.

<cfset CrLf = chr(10) & chr(13)>

Next, we use the FileExists() function to check to see if RunningLog.txt exists. If it does exist, we'll loop through it outputting the lines to the page. Otherwise, we output "You have apparently never been running."

<cfif FileExists(RunningLogPath)>

Next, we use the <cffile> tag to read the contents of the file into the myfile variable.

<cffile action="read" file="#RunningLogPath#" variable="myfile">

Finally, we loop through the file using the CrLf variable as the delimiter.

<cfloop list="#myfile#" index="run" delimiters="#CrLf#"> <cfoutput>#run#<br></cfoutput> </cfloop>

Writing and Appending to Files

When writing or appending to a file, <cffile> requires three attributes:

<cffile> Attributes for Writing Files
Attribute Description
action Must be set to write or append.
file The absolute path to the file to write.
output The text to write to the file.

The addnewline attribute is also useful. It takes a Yes/No value and determines whether a hard return should be appended to the output.

Note: When ColdFusion tries to append to a file that doesn't exist, it will create the file if it has permission to do so and the specified directory exists.

Uploading a New File

When uploading a new file, <cffile> requires three attributes:

<cffile> Attributes for Uploading Files
Attribute Description
action Must be set to upload.
fileField The form variable that contains the uploaded file.
destination The absolute path to the directory in which to save the file.

Two other useful, but not required, attributes are nameconflict and accept.

Additional <cffile> Attributes for Uploading Files
Attribute Description
nameconflict Possible values are error, overwrite, skip, and makeunique. error is the default.
accept A list of file types that the can be uploaded.

The following demo allows a user to upload a new log file to the Logs directory. The screenshot below shows the form.

And here is the results page.

Code Sample:

FilesAndDirs/Demos/AddLog.cfm
<html>
<head>
  <title>Add New Log</title>
</head>
<body>

<cfif isDefined("FORM.submitted")>
	<cfset uploaddir = ExpandPath("Logs")>
	<cffile action="upload" filefield="FORM.logfile"
				destination="#uploaddir#" accept="text/plain"
				nameconflict="#FORM.conflict#">
	<h2>Log Added</h2>
	<a href="RunningLogList.cfm">See All Running Logs</a>

<cfelse>
<h1>Add New Log</h1>
<cfoutput>
<form method="post" enctype="multipart/form-data" action="#CGI.SCRIPT_NAME#">
</cfoutput>
<input type="hidden" name="submitted" value="true">
<p>Log: <input type="file" name="logfile" accept="text/plain"></p>
<p>What do you want to do if a file by this name already exists?</p>
<select name="conflict">
	<option value="makeunique">Create New Name</option>
	<option value="overwrite">Overwrite Existing File</option>
	<option value="error">Don't Overwrite and Report Error</option>
	<option value="skip">Don't Overwrite and Ignore</option>
</select>
<p align="center"><input type="submit" value="Add Log"></p>
</form>

</cfif>

</body>
</html>

Things to note about this code:

  • This page has a self-submitting form.
  • The <form> tag takes the attribute enctype with the value set to multipart/form-data. This allows file uploads.
  • The form has a file input field, which allows the user to browse to a file on the client machine. The <cffile> tag uses this form variable as its filefield.
  • The form has a select menu, which allows the user to determine how a file name conflict is handled. The <cffile> tag uses this form variable as the value of its nameconflict attribute.

Writing to a File

Duration: 15 to 25 minutes.

In this exercise you will write code to append entries to the RunningLog.txt.

  1. Open FilesAndDirs/Exercises/AddEntry.cfm in your editor.
  2. Write code to save the entry in Logs/RunningLog.txt.

Code Sample:

FilesAndDirs/Exercises/AddEntry.cfm
<html>
<head>
  <title>Running Log</title>
</head>
<body>

<!---
	Check to see if the form has been submitted.
--->
<cfif WRITE_CONDITION_HERE>
<!---
	Write code to append the entry to Logs/RunningLog.txt
--->
	<h1 align="center">Entry added</h1>
	<a href="RunningLog.cfm">Running Log</a>
</cfif>

<h1 align="center">Add Entry</h1>
<cfoutput><form method="post" action="#CGI.SCRIPT_NAME#"></cfoutput>
<input type="hidden" name="submitted" value="true">
<table>
<tr>
	<td>Date:</td>
	<td><input type="text" name="date" size="20"></td>
</tr>
<tr>
	<td>Distance:</td>
	<td><input type="text" name="distance" size="20"></td>
</tr>
<tr>
	<td>Time:</td>
	<td><input type="text" name="time" size="20"></td>
</tr>
<tr>
	<td>Comments:</td>
	<td><input type="text" name="comments" size="50"></td>
</tr>
<tr>
	<td colspan="2" align="right">
		<input type="submit" name="Add Entry">
	</td>
</tr>
</table>
</form>

</body>
</html>

Add errror handling (not shown in solution).

Solution:

FilesAndDirs/Solutions/AddEntry.cfm
<html>
<head>
  <title>Running Log</title>
</head>
<body>

<cfif isDefined("FORM.submitted")>
	<cfset RunningLogPath = ExpandPath("Logs/RunningLog.txt")>
	<cfset Tab = chr(9)>
	<cfset outputstring = "#FORM.date##Tab##FORM.distance##Tab##FORM.time##Tab##FORM.comments#">
	
	<cffile action="append" file="#RunningLogPath#" output="#outputstring#" addnewline="yes">
	<h1 align="center">Entry added</h1>
	<a href="RunningLog.cfm">Running Log</a>
</cfif>

<h1 align="center">Add Entry</h1>
---- C O D E   O M I T T E D ----

File Functions

The table below shows some useful ColdFusion file functions.

File Functions
Function Explanation
FileExists(path_to_file) Returns true if the file exists; false if it doesn't.
ExpandPath(path_to_file) Returns an absolute path to the file.
GetFileFromPath(path_to_file) Returns the file name from an absolute path.

Using <cfdirectory>

The <cfdirectory> tag is used for working with directories. The action attribute of <cfdirectory> dictates what action will be performed on the directory in question. The table below describes the different actions that can be performed.

<cfdirectory> Actions
Action Description
list Reads the contents of a directory on the server into a query object.
create Creates a new directory on the server.
move Moves a directory on the server from one location to another.
rename Renames (or moves) a directory on the server.

Listing Directory Contents

The following demo shows how to list the contents in a directory with <cfdirectory>.

Code Sample:

FilesAndDirs/Demos/RunningLogList.cfm
<html>
<head>
<title>Running Logs</title>
</head>
<body>
<h1>Running Logs</h1>
<cfdirectory action="list" directory="#ExpandPath('Logs')#" name="loglist">

<table border="1">
<tr>
	<th>File Name</th>
	<th>File Size</th>
	<th>File or Directory</th>
	<th>Date Last Modified</th>
</tr>
	<cfoutput query="loglist">
	<tr>
		<td><a href="RunningLog-2.cfm?log=#name#">#name#</a></td>
		<td>#size#</td>
		<td>#type#</td>
		<td>#DateLastModified#</td>
	</tr>
	</cfoutput>
</table>
</body>
</html>

Things to note about this code:

  • The ExpandPath() function is used in the directory attribute of the <cfdirectory> tag to find the absolute path to the logs file.
  • <cfdirectory> returns the directory list as a query object just as a query to a database would. The <cfoutput> tag is used with the query attribute set to the name specified in <cfdirectory> to loop through the directory contents.
  • Columns of the result set returned by <cfdirectory> include Name, Size, Type, DateLastModified.
  • The file name is linked to RunningLog-2.cfm with the file name sent on the query string.

RunningLog-2.cfm is the same as RunningLog.cfm except that the file it reads is determined from the value passed in the query string. The code follows.

Code Sample:

FilesAndDirs/Demos/RunningLog-2.cfm
               <cfparam name="URL.log" default="RunningLog.txt">
<html>
<head>
  <title>Running Log</title>
</head>
<body>
<h1>Running Log</h1>
<a href="AddEntry.cfm">Add Entry</a><hr/>
<cfset RunningLogPath = ExpandPath("Logs/#URL.log#")>
<cfset CrLf = chr(10) & chr(13)>
<cfif FileExists(RunningLogPath)>
	<cffile action="read" file="#RunningLogPath#" variable="myfile">
	<cfloop list="#myfile#" index="run" delimiters="#CrLf#">
		<cfoutput>#run#<br></cfoutput>
	</cfloop>
<cfelse>
	You have apparently never been running.
</cfif>

</body>
</html>

Directory Functions

The table below shows some useful ColdFusion directory functions.

Directory Functions
Function Explanation
DirectoryExists(path_to_dir) Returns true if the directory exists; false if it doesn't.
ExpandPath(path_to_dir) Returns an absolute path to the directory.
GetDirectoryFromPath(path_to_dir) Returns the directory from an absolute path.