Working with Files and Directories
- 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.
Most Web applications use databases to store large amounts of data. However, in some cases, it will be necessary to store data in or access data from files. In this lesson, you will learn how to read from and write to files on the server.
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.
| 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:
| 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 of the ColdFusion tutorial, 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:
| 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.
Exercise: Writing to a File
In this exercise you will write code to append entries to the RunningLog.txt.
- Open FilesAndDirs/Exercises/AddEntry.cfm in your editor.
- 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).
Uploading a New File
When uploading a new file, <cffile> requires three attributes:
| 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.
| 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.
File Functions
The table below shows some useful ColdFusion 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.
| 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.
| 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. |
Working with Files and Directories Conclusion
In this lesson of the ColdFusion tutorial, you have learned to read from and manipulate files and directories on the server. Although writing to and reading from files can be useful in certain situations, when it is important to be able to access and change data quickly and to maintain the integrity of that data, it is often better to use a database. We will learn about databases later in the course.