Welcome to our free ColdFusion MX tutorial. This tutorial is based on Webucator's Comprehensive ColdFusion Training course.
Lesson Goals
<cffile>
to read from and write to files.<cfdirectory>
to list the contents of a directory.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. |
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, we will be working with FilesAndDirs/Logs/RunningLog.txt, which is a tab-delimited text file. Each line is formatted as follows:
The file is divided into "columns" using tabs (chr(9)) and rows using hard returns (chr(10)chr(13)). The file is shown below.
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.
<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.
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.
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."
Next, we use the <cffile>
tag to read the contents of the file into the myfile
variable.
Finally, we loop through the file using the CrLf
variable as the delimiter.
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.
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.
<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:
<form>
tag takes the attribute enctype
with the value set to
multipart/form-data
. This allows file uploads.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
.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.In this exercise you will write code to append entries to the RunningLog.txt.
<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).
<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 ----
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. |
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. |
The following demo shows how to list the contents in a directory with <cfdirectory>.
<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:
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.<cfdirectory>
include Name
, Size
,
Type
, DateLastModified
.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.
<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>
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. |