ColdFusion Read File

You can use ColdFusion's <cffile> tag to read a file from the server.

To read a file, you use the <cffile> tag to write the contents of the file to a variable. Once you've done that, it's up to you what you do with the contents of that variable. You can display it to the user, or you could insert it into a database (using the <cfquery> tag). It's also quite likely that you will want to manipulate the contents before you do anything with it.

Here's an example of reading an HTML file from the server, then outputting its contents:

Given this is an HTML file, the contents are interpreted by the browser:

My Shopping List

  • Bananas
  • Beans
  • Vegemite
  • Bread
  • Rolled Oats

If we wanted to view the source code, we could use ColdFusion's htmlCodeFormat() function when we output the results:

This results in:

<h3>My Shopping List</h3>
<li>Rolled Oats</li>

Binary Files

To read a binary file (such as an image or a word processing document), you need use action="readbinary". Although this puts the contents into a variable, you can't actually display the contents using the cfoutput tag.

You can still insert it into the database, or write it to another file. If you need to display the contents of a binary file, this can be achieved using the <cfcontent> tag (but I'll save that for another lesson).


Here's the full syntax of <cffile="read">:

For a more detailed explanation, see Adobe's documentation for cffile="read".

Next lesson shows you how to write files with ColdFusion.