View comments | RSS feed

Using cffile

You can use the cffile tag to work with files on the server in several ways:

You use the action attribute to specify any of the following file actions: upload, move, rename, copy, delete, read, readBinary, write, and append. The required attributes depend on the action specified. For example, if action="write", ColdFusion expects the attributes associated with writing a text file.

Note:   Consider the security and logical structure of directories on the server before allowing users access to them. You can disable the cffile tag in the ColdFusion Administrator. Also, to access files that are not located on the local ColdFusion Server system, ColdFusion services must run using an account with permission to access the remote files and directories.

Uploading files

File uploading requires that you create two files:

The following procedures describe how to create these files.

To create an HTML file to specify file upload information:

  1. Create a ColdFusion page with the following content:
    <head><title>Specify File to Upload</title></head>
    <body>
    <h2>Specify File to Upload</h2>
    <!--- the action attribute is the name of the action page --->
    <form action="uploadfileaction.cfm" 
        enctype="multipart/form-data" 
        method="post">
      <p>Enter the complete path and filename of the file to upload:
      <input type="file"
          name="FiletoUpload"
          size="45">
      </p>
      <input   type="submit"
          value="Upload">
    </form>
    </body>
    
  2. Save the file as uploadfileform.cfm in the myapps directory under your web_root and view it in the browser:

    The file uploadfiletoform.cfm rendered in a browser.

Note:   The form will not work until you write an action page for it (see the next procedure).

Reviewing the code

The following table describes the code and its function:
Code
Description
<form action="uploadfileaction.cfm"
	enctype="multipart/form-data"
	method="post">
Create a form that contains file selection fields for upload by the user. The action attribute value specifies the ColdFusion template that will process the submitted form. The enctype attribute value tells the server that the form submission contains an uploaded file. The method attribute is set to post to submit a ColdFusion form.
<input type="file"
	name="FiletoUpload"
	size="45">
Allow the user to specify the file to upload. The file type instructs the browser to prepare to read and transmit a file from the user's system to your server. It automatically includes a Browse button to allow the user to look for the file instead of manually entering the entire path and filename.

The user can enter a file path or browse the system and select a file to send.

  1. Create a ColdFusion page with the following content:
    <html>
    <head> <title>Upload File</title> </head>
    <body>
    <h2>Upload File</h2>
    
    <cffile action="upload"
        destination="c:\temp\"
        nameConflict="overwrite"
        fileField="Form.FiletoUpload">
        
    <cfoutput>
    You uploaded #cffile.ClientFileName#.#cffile.ClientFileExt#
          successfully to #cffile.ServerDirectory#.
    </cfoutput>
    
    </body>
    </html>
    
  2. Change the following line to point to an appropriate location on your server:
    destination="c:\temp\"
    

    Note:   This directory must exist on the server.

  3. Save the file as uploadfileaction.cfm in the myapps directory under your web_root.
  4. View uploadfileform.cfm in the browser, enter a file to upload, and submit the form.

    The file you specified uploads, as the following figure shows:

    The results of uploading the file.

Reviewing the code

The following table describes the code and its function:
Code
Description
<cffile action="upload"
Output the name and location of the uploaded file on the client machine.
destination="c:\temp\"
Specify the destination of the file.
nameConflict="overwrite"
If the file already exists, overwrite it.
fileField="Form.FiletoUpload">
Specify the name of the file to upload. Do not enclose the variable in pound signs.
You uploaded #cffile.ClientFileName#.#cffile.
ClientFileExt# successfully to
#cffile.ServerDirectory#.
Inform the user of the file that was uploaded and its destination. For information on cffile scope variables, see "Evaluating the results of a file upload".

Note:   This example performs no error checking and does not incorporate any security measures. Before deploying an application that performs file uploads, be sure to incorporate both error handling and security. For more information, see Chapter 16, "Securing Applications" and Chapter 14, "Handling Errors".

Resolving conflicting filenames

When you save a file to the server, there is a risk that a file with the same name might already exist. To resolve this problem, assign one of these values to the nameConflict attribute of the cffile tag:

Controlling the type of file uploaded

For some applications, you might want to restrict the type of file that is uploaded. For example, you might not want to accept graphic files in a document library.

You use the accept attribute to restrict the type of file that you allow in an upload. When an accept qualifier is present, the uploaded file's MIME content type must match the criteria specified or an error occurs. The accept attribute takes a comma-separated list of MIME data names, optionally with wildcards.

A file's MIME type is determined by the browser. Common types, such as image/gif and text/plain, are registered in the browser.

Note:   Modern versions of Internet Explorer and Netscape support MIME type associations. Other browsers and older versions might ignore these associations.

ColdFusion saves any uploaded file if you omit the accept attribute or specify "*/*". You can restrict the file types, as demonstrated in the following examples.

The following cffile tag saves an image file only if it is in the GIF format:

<cffile action="Upload"
  fileField="Form.FiletoUpload"
  destination="c:\uploads\"
  nameConflict="Overwrite"
  accept="image/gif">

The following cffile tag saves an image file only if it is in GIF or JPEG format:

<cffile action="Upload"
  fileField="Form.FiletoUpload"
  destination="c:\uploads\"
  nameConflict="Overwrite"
  accept="image/gif, image/jpeg"> 

Note:   If you receive an error similar to "The MIME type of the uploaded file (image/jpeg) was not accepted by the server", enter accept="image/pjpeg" to accept JPEG files.

This cffile tag saves any image file, regardless of the format:

<cffile action="Upload"
  fileField="Form.FiletoUpload"
  destination="c:\uploads\"
  nameConflict="Overwrite"
  accept="image/*">

Setting file and directory attributes

In Windows, you specify file attributes using the cffile attributes attribute. In UNIX, you specify file or directory permissions using the mode attribute of the cffile or cfdirectory tag.

Windows

In Windows, you can set the following file attributes:

To specify several attributes in CFML, use a comma-separated list for the attributes attribute; for example, attributes="ReadOnly,Archive". If you do not use attributes, the file's existing attributes are maintained. If you specify any other attributes in addition to Normal, the additional attribute overrides the Normal setting.

UNIX

In UNIX, you can individually set permissions on files and directories for each of three types of users-owner, group, and other. You use a number for each user type. This number is the sum of the numbers for the individual permissions allowed. Values for the mode attribute correspond to octal values for the UNIX chmod command:

You enter permissions values in the mode attribute for each type of user: owner, group, and other in that order. For example, use the following code to assign read permissions for everyone:

mode=444

To give a file or directory owner read/write/execute permissions and read only permissions for everyone else:

mode=744

Evaluating the results of a file upload

After a file upload is completed, you can retrieve status information using file upload status variables. This status information includes data about the file, such as its name and the directory where it was saved.

You can access file upload status variables using dot notation, using either file.varname or cffile.varname. Although you can use either the File or cffile prefix for file upload status variables, cffile is preferred; for example, cffile.ClientDirectory. The File prefix is retained for backward compatibility.

Note:   File status variables are read-only. They are set to the results of the most recent cffile operation. If two cffile tags execute, the results of the first are overwritten by the subsequent cffile operation.

The following table describes the file upload status variables that are available after an upload:
Variable
Description
attemptedServerFile
Initial name that ColdFusion uses when attempting to save a file; for example, myfile.txt. (see "Resolving conflicting filenames").
clientDirectory
Directory on the client's system from which the file was uploaded.
clientFile
Full name of the source file on the client's system with the file extension; for example, myfile.txt.
clientFileName
Name of the source file on the client's system without an extension; for example, myfile.
clientFileExt
Extension of the source file on the client's system without a period; for example, txt (not .txt).
contentType
MIME content type of the saved file; for example, image for image/gif.
contentSubType
MIME content subtype of the saved file; for example, gif for image/gif.
dateLastAccessed
Date that the uploaded file was last accessed.
fileExisted
Indicates (Yes or No) whether the file already existed with the same path.
fileSize
Size of the uploaded file.
fileWasAppended
Indicates (Yes or No) whether ColdFusion appended the uploaded file to an existing file.
fileWasOverwritten
Indicates (Yes or No) whether ColdFusion overwrote a file.
fileWasRenamed
Indicates (Yes or No) whether the uploaded file was renamed to avoid a name conflict.
fileWasSaved
Indicates (Yes or No) whether ColdFusion saved the uploaded file.
oldFileSize
Size of the file that was overwritten in the file upload operation. Empty if no file was overwritten.
serverDirectory
Directory where the file was saved on the server.
serverFile
Full name of the file saved on the server with the file extension; for example, myfile.txt.
serverFileName
Name of the file saved on the server without an extension; for example, myfile.
serverFileExt
Extension of the file saved on the server without a period; for example, txt (not .txt).
timeCreated
Date and time the uploaded file was created.
timeLastModified
Date and time of the last modification to the uploaded file.

Moving, renaming, copying, and deleting server files

With cffile, you can create application pages to manage files on your web server. You can use the tag to move files from one directory to another, rename files, copy a file, or delete a file.

The examples in the following table show static values for many of the attributes. However, the value of all or part of any attribute in a cffile tag can be a dynamic parameter.
Action
Example code
Move a file
<cffile action="move"
	source="c:\files\upload\KeyMemo.doc"
	destination="c:\files\memo\">
Rename a file
<cffile action="rename"
	source="c:\files\memo\KeyMemo.doc"
	destination="c:\files\memo\OldMemo.doc">
Copy a file
<cffile action="copy"
	source="c:\files\upload\KeyMemo.doc"
	destination="c:\files\backup\">
Delete a file
<cffile action="delete"
	file="c:\files\upload\oldfile.txt">

This example sets the archive bit for the uploaded file:

<cffile action="Copy"
  source="c:\files\upload\keymemo.doc"
  destination="c:\files\backup\"
  attributes="Archive">

Note:   Ensure you include the trailing slash (\) when you specify the destination directory. Otherwise, ColdFusion treats the last element in the pathname as a filename. This only applies to copy actions.

Reading, writing, and appending to a text file

In addition to managing files on the server, you can use cffile to read, create, and modify text files. As a result, you can do the following things:

Reading a text file

You can use cffile to read an existing text file. The file is read into a local variable that you can use anywhere in the application page. For example, you could read a text file and then insert its contents into a database, or you could read a text file and then use one of the string replacement functions to modify the contents.

To read a text file:

  1. Create a ColdFusion page with the following content:
    <html>
    <head>
      <title>Read a Text File</title>
    </head>
    
    <body>
    Ready to read the file:<br>
    <cffile action="read"
      file="C:\inetpub\wwwroot\mine\message.txt"
      variable="Message">
    
    <cfoutput>
      #Message#
    </cfoutput>
    </body>
    </html>
    
  2. Replace C:\inetpub\wwwroot\mine\message.txt with the location and name of a text file on the server.
  3. Save the file as readtext.cfm in the myapps directory under your web_root and view it in the browser:

    Results of viewing readtext.cfm in a browser.

Writing a text file on the server

You can use cffile to write a text file based on dynamic content. For example, you could create static HTML files or log actions in a text file.

To create a form in to capture data for a text file:

  1. Create a ColdFusion page with the following content:
    <html>
    <head>
      <title>Put Information into a Text File</title>
    </head>
    
    <body>
    <h2>Put Information into a Text File</h2>
    
    <form action="writetextfileaction.cfm" method="Post">
      <p>Enter your name: <input type="text" name="Name" size="25"></p>
      <p>Enter the name of the file: <input type="text" name="FileName" size="25">.txt</p>
      <p>Enter your message:
      <textarea name="message"cols=45 rows=6></textarea>
      </p>
      <input type="submit" name="submit" value="Submit"> 
    </form>
    </body>
    </html>
    
  2. Save the file as writetextfileform.cfm in the myapps directory under your web_root.

Note:   The form will not work until you write an action page for it (see the next procedure).

To write a text file:

  1. Create a ColdFusion page with the following content:
    <html>
    <head>
      <title>Write a Text File</title>
    </head>
    <body>
    <cffile action="write"
      file="C:\inetpub\wwwroot\mine\#Form.FileName#.txt"
      output="Created By: #Form.Name#
    #Form.Message# ">
    </body>
    </html>
    
  2. Modify the path C:\inetpub\wwwroot\mine\ to point to a path on your server.
  3. Save the file as writetextfileaction.cfm in the myapps directory under your web_root.
  4. View the file writetextfileform.cfm in the browser, enter values, and submit the form; as shown in the following figure.

    Submitting form with data for filed values.

    The text file is written to the location you specified. If the file already exists, it is replaced.

Appending a text file

You can use cffile to append additional text to the end of a text file; for example, when you create log files.

To append a text file:

  1. Open the writetextfileaction.cfm file in ColdFusion Studio.
  2. Change the value for the action attribute from write to append so that the file appears as follows:
    <html>
    <head>
      <title>Append a Text File</title>
    </head>
    <body>
    <cffile action="append"
      file="C:\inetpub\wwwroot\mine\message.txt"
      output="Appended By: #Form.Name#">
    </body>
    </html>
    
  3. Save the file as writetextfileaction.cfm in the myapps directory under your web_root.
  4. View the file in the browser, enter values, and submit the form.

    The appended information displays at the end of the text file.

ColdFusion 9 | ColdFusion 8 | ColdFusion MX 7 | ColdFusion MX 6.1 | ColdFusion MX | Forums | Developer Center | Bug Reporting

Version 6

Comments are no longer accepted for ColdFusion MX. ColdFusion 8 is the current version.

Comments


kelleymertig said on Nov 20, 2003 at 8:53 AM :
There is no information for solving problems such as destination does not exist for action="upload". I have had nothing but problems with the <CFFILE>, and there are no tips or explanations for the errors that could occur.
No screen name said on Feb 2, 2004 at 8:38 AM :
PLEASE HELP!!

Am a desperate Mac user with the fabulous coldfusion installed along
side my trusty dreamweaver - feel I am bang up to date and need to
build a site allowing my client to upload images themselves but i need to
work out a way of resizing the images on upload so they are all uniform
in size. Have searched the web and can only find tutorials or extensions
for ASP users - not much use for my eMac and Powerbook who are sat
sulking in the corner! I would be truly grateful if you could help as I am
sure this can be done in coldfusion.
Thanks.
HorsePunchKid said on Feb 11, 2004 at 12:52 PM :
Re: Resizing an image after upload

This should be possible. First get the file uploaded as described in the documentation here. Then run something like ImageMagick (you can find their website easily) using the cfexecute tag. If you go with ImageMagick, you basically just pass the name of the file you just uploaded and the size you want the image to be using the "arguments" attribute. Good luck!
beefo said on Apr 22, 2004 at 9:11 AM :
Hey No screen name, you can also try to take a look at ImageJ.cfc made By Ben Hediard on www.benorama.com ... I use it and it's very very cool.....you can do a lot of stuff as drawing lines, cropping, add text, rotating and of course resizing.... Give it a try !
No screen name said on Jun 12, 2004 at 6:50 PM :
I need help using the cffile in conjunction with an insert form. I have created a form that inserts records into a database and also a form that uploads an image file, but can't seem to merge the two forms into one. When I do, the page errors out saying there is no field in the database for the image file...which there isn't.
No screen name said on Jul 10, 2004 at 2:28 AM :
For the Action Page -> Try CFFILE first to upload the image, and then cfquery in order to insert values for the record, including the path of the image, maybe that will do it.....
No screen name said on Jul 10, 2004 at 2:33 AM :
Hey.. I was wondering if one of you knows how CF, can only list directories and files, instead of using the submit button of type file..

The reason why I am asking is because I would like CF to return this list back to Flash... And let Flash immitate the Window File Search Box...
JDR said on Aug 10, 2004 at 9:21 AM :
I need to know if the file object gets set when I do a move. I need to be able to find out if the file has been renamed due to the makeunique option.
halL said on Aug 11, 2004 at 7:52 AM :
cffile action="move" does not use the makeunique attribute.
If you specify the attribute, ColdFusion MX ignores it and overwrites any identically named files.

Only cffile action="upload" uses the makeunique attribute.
The cffile structure that is available after you use the upload attribute (and only after using the cffile tag with this attribute) includes a fileWasRenamed field with the information you want.
The full contents of this structure is listed on this page.
Matt Topas said on Sep 27, 2004 at 9:03 AM :
I'm trying to copy or move with CFFILE and keep receiving an error:
"The system cannot find the file specified" and specifies the source file. The copy or move succeeds but I still receive the error/warning! I don't get it with all kinds of file. It seems tab delimited files are ok but the comma delimited file gets this response.
No screen name said on Nov 29, 2004 at 11:56 PM :
If I use this code as the destination 'C:\inetpub\wwwroot\mine\', sure i can upload the file successfully. But, how about if i post the page to the web and use it with other computer? I think, it's not a right path. And what is the path of the server actually? I try many of the path but still can't work.
~JOSh-X said on Dec 8, 2004 at 3:33 PM :
Can CFFile upload to a directory that contains periods?

For example, I have my directory structure set as follows:

C:\myWeb\josh.websites.comPload

I want to upload to that directory. But when I try to, CF is giving me an error:
CFCATCH INFO:
Type: java.lang.StringIndexOutOfBoundsException
Message: String index out of range: -9
Detail:

Thanks in advance for any help you can offer!

~JOSh-X
~JOSh-X said on Dec 14, 2004 at 9:23 AM :
To answer my own question: yes! CFFile can upload to a directory that contains periods.

The Java error it was spitting out was because the directory didn't exist. (Great error guys :-/ blah)

I changed the directory to:
C:\my Web\josh.websites.comPload

and it worked fine.

~JOSh-X
Libby said on Jan 24, 2005 at 11:24 AM :
Other than the Forums, is there a place to go and register and/or find out answers to some questions regarding the changes of CFFILE between 5 and MX? Some of the functionality that worked in 5 dosen't work in MX (6.1 Updater), and the code analyzer doesn't catch problems. Specifically, a move with CFFILE and keep receiving an error: "The system cannot find the file specified" and specifies the source file. Point me in the right direction, please!
ASandstrom said on Feb 4, 2005 at 11:21 AM :
For a concise history of CFML, you can go to this link on the Macromedia site:
http://www.macromedia.com/cfusion/knowledgebase/index.cfm?event=view&id=KC.tn_18791&extid=tn_18791&dialogID=2564542&iterationID=1&sessionID=48306d787f63$3FI$3F$&stateID=0%200%202566724&mode=simple
To see the migration guide, use this link:
http://www.macromedia.com/devnet/mx/coldfusion/articles/_misc_blurbs/migrating.pdf
Casey D said on Jul 20, 2005 at 4:09 PM :
search http://www.tek-tips.com/threadminder.cfm?pid=232
Really dope CFML posse over there and as you see... Site is built on CF

 

RSS feed | Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/coldfusion/6/Developing_ColdFusion_MX_Applications_with_CFML/manageFiles3.htm