ColdFusion
  Home arrow ColdFusion arrow Page 5 - Introduction to ColdFusion Markup Language...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Actuate Whitepapers 
VeriSign Whitepapers 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
COLDFUSION

Introduction to ColdFusion Markup Language, concluded
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 5
    2006-01-26

    Table of Contents:
  • Introduction to ColdFusion Markup Language, concluded
  • Query Loop
  • Collection Loop
  • The cfdirectory tag
  • The cffile tag
  • The cfform tag

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Free Web 2.0 Code Generator! Generate data entry and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    Introduction to ColdFusion Markup Language, concluded - The cffile tag


    (Page 5 of 6 )

    Like<cfdirectory>, this tag is often disabled in shared hosting environments because of its potentially destructive effects. Exercise caution when working with this tag, because it is all too easy to delete the wrong file in the wrong directory if you are not careful.

    ColdFusion offers a<cffile>tag that works in a way similar to<cfdirectory>, providing similar functionality for files within directories.<cffile>manipulates files on the server by using nine distinct actions:upload,copy,move,rename,delete,append,write,read, andreadbinary. Lets go through each of these now.

    upload

    ColdFusion allows users to upload files to the server easily by using the HTML form element<input type="file">. When a user submits the form, the file is sent to the server, and you are able to upload the file using code like the following snippet:

    <cffile action="upload" filefield="MyFile"
            destination="#ExpandPath( '.' )#"
            nameconflict="makeunique">

    This will upload the file that was passed to this page in an<input type="file" name="MyFile">form field, and will upload the file to the same directory as the.cfmfile with the<cffile action="upload">code in it.

    The final attribute,nameconflict, tells ColdFusion how to deal with the file upload if there is already a file with that name. There are four possible values:

    1. Error: ColdFusion throws an error if a file with this name already exists in the directory.
    2. Skip: The file will not be uploaded. ColdFusion just ignores it.
    3. Overwrite: The older file is overwritten by the newer file.
    4. Makeunique: If a file already exists with this name, ColdFusion creates a unique filename for the newer file.

    Well cover this action in more detail in Chapter 5.

    copy

    This action allows us to copy an existing file and assign it a new name. You can see an example of the copy action here:

    <cffile action="copy"
            destination="#ExpandPath( '.\index_copy.cfm' )#"
            source="#ExpandPath( '.\index.cfm' )#">

    This code snippet makes a copy of theindex.cfmfile in the current folder and names the new fileindex_copy.cfm. The file is then saved to the same folder. If there is already a file with the same name and path as the destination file, it will be overwritten.

    To check to see if a file already exists, we can use a function called#FileExists()#.#FileExists()#takes a single parameter, which is a fully qualified path to the file. Here's an example of this (filecopy.cfm):

    <cfif NOT FileExists( ExpandPath( '.\index_copy.cfm' ) )>
      <cffile action="copy" destination="#ExpandPath( '.\index_copy.cfm' )#"
              source="#ExpandPath( '.\index.cfm' )#">
    </cfif>

    If you create this file inside yourcfbookdirectory, a copy of theindex.cfmfile,index_copy.cfm, will be created in the same directory.

    move

    Themoveaction simply moves a file, either within the same directory or to a different folder on the server. The most basic usage of this action is shown here (filemove.cfm):

    <cffile action="move"
            destination="#ExpandPath( '.\archive\' )#"
            source="#ExpandPath( '.\index.cfm' )#">

    This snippet takes the file defined in the source attribute and moves it to the location defined in the destination attribute. In this example, we copy theindex.cfmin the current directory into a subfolder namedarchive. This file will keep the same name in the new folder. If there is already a file namedindex.cfmin the destination directory, it will be overwritten by the file we move.

    You can rename files while moving them by simply adding a filename to the end of the destination attribute (filemove2.cfm):

    <cffile action="move"
            destination="#ExpandPath( '.\archive\old_index.cfm' )#"
            source="#ExpandPath( '.\index.cfm' )#">

    The preceding code takes theindex.cfmfile from the current directory, moves it to a subfolder calledarchive, and renames the fileold_index.cfm.

    It is important to note that the destination folder must exist prior to calling this action. If you don't already have a subfolder namedarchive in the current directory, then ColdFusion will throw an error.

    rename

    You have already seen how to rename files using the move action, but you can also use therenameaction. The way that you use this action is almost exactly the same, as shown here (filerename.cfm):

    <cffile action="rename"
            destination="#ExpandPath( '.\old_index.cfm' )#"
            source="#ExpandPath( '.\index.cfm' )#">

    This code renames the currentindex.cfmfile toold_index.cfm.

    delete

    Thedeleteaction simply deletes the file specified in the file attribute. The basic usage is shown here (filedelete.cfm):

    <cffile action="delete"
            file="#ExpandPath( '.\old_index.cfm' )#">

    Like the other tags, it requires a full path to the target file. If the file doesn't exist, ColdFusion will throw an error. Therefore, it is best to make sure that the file exists prior to calling this tag by using the#FileExists()#function outlined in the copy action earlier in this section.

    append

    Not surprisingly, theappend action appends text to an existing file. Let's make use of it now.

    1. Create a new file namedcreatelog.cfmin ourcfbookdirectory, and enter the following code into the Document window:

      <cffile action="append" 
              file="#ExpandPath( '.\log.cfm' )#"
              output="Hello World" addnewline="Yes">

    2. Opencreatelog.cfmfile in a web browser and reload the page a couple of times.
    3. If you then open thelog.cfmfile that is created, you will see that it contains text similar to the following:

      Hello World
      Hello World

    You'll notice that each time you refresh thecreatelog.cfmpage, a new line is added to thelog.cfm file. This technique can be useful if you want to create your own log files and record whenever a user performs a certain action. Or you might use this if you encounter an error and want to create a log file for an administrator to browse through to better understand how and why the error occurred.

    NOTE   you can use two other tags, <cflog> and <cftrace>, to assist in logging as well.

    If the file specified in thefileattribute doesnt exist prior to calling this tag, ColdFusion will create the file for you. If the file does exist, ColdFusion will append the text in the output attribute to the end of the file. The final attribute in the preceding listing,addnewline, controls whether ColdFusion should add a line break after writing the output to the file. In the preceding example, theaddnewlineattribute is set to Yes, so you only need to append Hello World to thelog.cfmfile, and a line break is added to the end of the output.

    If we set theaddnewlineattribute toNoand run the code again a couple times, we will observe that ColdFusion just appends the Hello World onto the end of the previous line, so our output will look similar to this:

    Hello WorldHello WorldHello World

    write

    Thewriteaction is very similar to the append action, but with one important difference. This action will overwrite the file if it already exists, rather than adding to the same file. The basic usage is shown here (createlog2.cfm):

    <cffile action="write"
            file="#ExpandPath( '.\log.cfm' )#"
            output="Hello World" addnewline="yes">

    If there is an existinglog.cfmfile in the current directory, calling this tag will destroy the contents of that file and simply writeHello Worldto the file. If the file does not exist prior to calling this tag, ColdFusion will automatically create the file for you.

    read

    Thereadaction reads a file and saves the content to a variable. Here's how you use it (readlog.cfm):

    <cffile action="read" 
            file="#ExpandPath( '.\log.cfm' )#" 
            variable="logfile">
    <cfoutput><pre>#logfile#</pre></cfoutput>

    This code reads the contents of the log.cfm file
    located in the current directory,
    saves its contents to a variable called #logfile#, and finally outputs the contents of the file to the browser window. If the file does not exist prior to calling this tag, ColdFusion will throw an error. It is best to check that the file exists prior to using this tag, which can be done by using code such as the following (readlog2.cfm):

    <cfset targetFile = ExpandPath( ".\filedoesntexist.cfm" )> 
    <cfif FileExists( targetFile )>
     
    <cffile action="read" file="#targetFile#" variable="logfile">    
     <cfoutput><pre>
    #logfile#</pre></cfoutput> 
     <cfelse>
     
    Unable to find file.
    </cfif>

    readbinary

    The final action,readbinary, is used to read the contents of binary files, such as images and executables, and store their contents in a ColdFusion variable. This action enables you to do such useful things as storing images in a database. An example of using this tag is as follows (readbinary.cfm):

    <cffile action="readbinary"
            file="#ExpandPath( '.\gn_mm_logo.gif' )#"
           
    variable="myImage">

    <cfoutput>#ToBase64( myImage )#</cfoutput>

    The preceding code snippet opens the GIF image, stores the binary information into a variable, and outputs a string representation to the screen. If you want to database the image file, you would need to write a query that stores the string in Base64 format using the#ToBase64()#function shown in the preceding code. To retrieve the image, you would need to write a query that selects the data from the database and then writes it to a temporary file before using<img src="">to display the newly created image. The #toString()# function is used to convert a Base64 representation to a string.

    More ColdFusion Articles
    More By Apress Publishing


       · This article is an excerpt from the book "ColdFusion Web Development with...
     

    Buy this book now. This article is excerpted from chapter three of the book ColdFusion Web Development with Dreamweaver MX 2004, written by Jen and Peter deHaan et al. (Apress; ISBN: 1590592379). Check it out today at your favorite bookstore. Buy this book now.

    COLDFUSION ARTICLES

    - How to Access a SQL Anywhere Database with C...
    - CFXML: Probing XMLDOM in ColdFusion
    - Creating a Web Service with ColdFusion: the ...
    - CFAjax: What it is and How to Use it
    - Querying SQL 2000 Server from ColdFusion
    - Introduction to ColdFusion Markup Language, ...
    - Introduction to ColdFusion Markup Language
    - Databases and Dreamweaver MX 2004, concluded
    - Databases and Dreamweaver MX 2004
    - Welcome to Coldfusion MX 6.1, concluded
    - Welcome to Coldfusion MX 6.1
    - What You Must Know About ColdFusion Flow-Con...
    - What You Must Know About Operators in ColdFu...
    - Everything You Must Know About ColdFusion Va...
    - My First Application on ColdFusion MX Server


    Iron Speed





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway