- CFML Reference User Guide
- ColdFusion functions
- ColdFusion functions by category
- Functions a-b
- Abs
- ACos
- AddSOAPRequestHeader
- AddSOAPResponseHeader
- AjaxLink
- AjaxOnLoad
- ApplicationStop
- ArrayAppend
- ArrayAvg
- ArrayClear
- ArrayContains
- ArrayContainsNoCase
- ArrayDelete
- ArrayDeleteAt
- ArrayDeleteNoCase
- ArrayEach
- ArrayFilter
- ArrayFind
- ArrayFindAll
- ArrayFindAllNoCase
- ArrayFindNoCase
- ArrayInsertAt
- ArrayIsDefined
- ArrayIsEmpty
- ArrayLen
- ArrayMap
- ArrayMax
- ArrayMin
- ArrayNew
- ArrayPrepend
- ArrayReduce
- ArrayResize
- ArraySet
- ArraySetMetadata
- ArraySlice
- ArraySort
- ArraySum
- ArraySwap
- ArrayToList
- Asc
- ASin
- Atn
- AuthenticatedContext
- AuthenticatedUser
- BinaryDecode
- BinaryEncode
- BitAnd
- BitMaskClear
- BitMaskRead
- BitMaskSet
- BitNot
- BitOr
- BitSHLN
- BitSHRN
- BitXor
- BooleanFormat
- Abs
- Functions-c-d
- CacheGet
- CacheGetAllIds
- CacheGetMetadata
- CacheGetProperties
- CacheGetSession
- CacheIdExists
- CachePut
- CacheRegionExists
- CacheRegionNew
- CacheRegionRemove
- CacheRemove
- CacheRemoveAll
- CacheSetProperties
- CallStackDump
- CallStackGet
- CanDeSerialize
- Canonicalize
- CanSerialize
- Ceiling
- CharsetDecode
- CharsetEncode
- Chr
- CJustify
- Compare
- CompareNoCase
- Cos
- CreateDate
- CreateDateTime
- CreateObject
- CreateObject: .NET object
- CreateObject: COM object
- CreateObject: component object
- CreateObject: CORBA object
- CreateObject: Java or EJB object
- CreateObject: web service object
- CreateODBCDate
- CreateODBCDateTime
- CreateODBCTime
- CreateSignedJWT
- CreateEncryptedJWT
- CreateTime
- CreateTimeSpan
- CreateUUID
- CSRFGenerateToken
- CSRFVerifyToken
- CSVRead
- CSVWrite
- CSVProcess
- DateAdd
- DateCompare
- DateConvert
- DateDiff
- DateFormat
- DatePart
- DateTimeFormat
- Day
- DayOfWeek
- DayOfWeekAsString
- DayOfYear
- DaysInMonth
- DaysInYear
- DE
- DecimalFormat
- DecodeForHTML
- DecodeFromURL
- DecrementValue
- Decrypt
- DecryptBinary
- DeleteClientVariable
- Deserialize
- DeserializeJSON
- DeserializeXML
- DirectoryCopy
- DirectoryCreate
- DirectoryDelete
- DirectoryExists
- DirectoryList
- DirectoryRename
- DollarFormat
- DotNetToCFType
- Duplicate
- Functions-e-g
- EncodeForCSS
- EncodeForDN
- EncodeForHTML
- EncodeForHTMLAttribute
- EncodeForJavaScript
- EncodeForLDAP
- EncodeForURL
- EncodeForXML
- EncodeForXMLAttribute
- EncodeForXpath
- Encrypt
- EncryptBinary
- EntityDelete
- EntityLoad
- EntityLoadByExample
- EntityLoadByPK
- EntityMerge
- EntityNew
- EntityReload
- EntitySave
- EntityToQuery
- Evaluate
- Exp
- ExpandPath
- FileClose
- FileCopy
- FileDelete
- FileExists
- FileGetMimeType
- FileIsEOF
- FileMove
- FileOpen
- FileRead
- FileReadBinary
- FileReadLine
- FileSeek
- FileSetAccessMode
- FileSetAttribute
- FileSetLastModified
- FileSkipBytes
- FileUpload
- FileUploadAll
- FileWrite
- FileWriteLine
- Find
- FindNoCase
- FindOneOf
- FirstDayOfMonth
- Fix
- Floor
- FormatBaseN
- GeneratePBKDFKey
- GenerateSecretKey
- GetApplicationMetadata
- GetAuthUser
- GetBaseTagData
- GetBaseTagList
- GetBaseTemplatePath
- GetClientVariablesList
- GetComponentMetaData
- GetContextRoot
- GetCPUUsage
- GetCurrentTemplatePath
- GetCSPNonce
- GetDirectoryFromPath
- GetEncoding
- GetException
- GetFileFromPath
- GetFileInfo
- GetFreeSpace
- GetFunctionCalledName
- GetFunctionList
- GetGatewayHelper
- GetHttpRequestData
- GetHttpTimeString
- GetK2ServerDocCount
- GetK2ServerDocCountLimit
- GetLocale
- GetLocaleDisplayName
- GetLocalHostIP
- GetMetaData
- GetMetricData
- GetPageContext
- GetPropertyString
- GetPropertyFile
- GetPrinterInfo
- GetPrinterList
- GetProfileSections
- GetProfileString
- GetReadableImageFormats
- GetSafeHTML
- GetSAMLAuthRequest
- GetSAMLLogoutRequest
- Generate3DesKey
- GenerateSAMLSPMetadata
- GetSOAPRequest
- GetSOAPRequestHeader
- GetSOAPResponse
- GetSOAPResponseHeader
- GetSystemFreeMemory
- GetSystemTotalMemory
- GetTempDirectory
- GetTempFile
- GetTemplatePath
- GetTickCount
- GetTimeZoneInfo
- GetToken
- GetTotalSpace
- GetUserRoles
- GetVFSMetaData
- GetWriteableImageFormats
- Functions-h-im
- Hash
- HMac
- Hour
- HQLMethods
- HTMLCodeFormat
- HTMLEditFormat
- IIf
- ImageAddBorder
- ImageBlur
- ImageClearRect
- ImageCopy
- ImageCreateCaptcha
- ImageCrop
- ImageDrawArc
- ImageDrawBeveledRect
- ImageDrawCubicCurve
- ImageDrawLine
- ImageDrawLines
- ImageDrawOval
- ImageDrawPoint
- ImageDrawQuadraticCurve
- ImageDrawRect
- ImageDrawRoundRect
- ImageDrawText
- ImageFlip
- ImageGetBlob
- ImageGetBufferedImage
- ImageGetEXIFMetadata
- ImageGetEXIFTag
- ImageGetHeight
- ImageGetIPTCMetadata
- ImageGetIPTCTag
- ImageGetMetadata
- ImageGetWidth
- ImageGrayscale
- ImageInfo
- ImageMakeColorTransparent
- ImageMakeTranslucent
- ImageNegative
- ImageNew
- ImageOverlay
- ImagePaste
- ImageRead
- ImageReadBase64
- ImageResize
- ImageRotate
- ImageRotateDrawingAxis
- ImageScaleToFit
- ImageSetAntialiasing
- ImageSetBackgroundColor
- ImageSetDrawingColor
- ImageSetDrawingStroke
- ImageSetDrawingTransparency
- ImageSharpen
- ImageShear
- ImageShearDrawingAxis
- ImageTranslate
- ImageTranslateDrawingAxis
- ImageWrite
- ImageWriteBase64
- ImageXORDrawingMode
- Functions-in-k
- IncrementValue
- InputBaseN
- Insert
- Int
- InterruptThread
- InvalidateOauthAccesstoken
- Invoke
- InitSAMLAuthRequest
- InitSAMLLogoutRequest
- InvokeCFClientFunction
- IsArray
- IsAuthenticated
- IsAuthorized
- IsBinary
- IsBoolean
- IsClosure
- IsCustomFunction
- IsDate
- IsDateObject
- IsDDX
- IsDebugMode
- IsDefined
- IsImage
- IsImageFile
- IsInstanceOf
- IsIPv6
- IsJSON
- IsK2ServerABroker
- IsK2ServerDocCountExceeded
- IsK2ServerOnline
- IsLeapYear
- IsLocalHost
- IsNull
- IsNumeric
- IsNumericDate
- IsObject
- isOnline
- IsPDFArchive
- IsPDFFile
- IsPDFObject
- IsProtected
- IsQuery
- isSamlLogoutResponse
- isSafeHTML
- IsSimpleValue
- IsSOAPRequest
- IsSpreadsheetFile
- IsSpreadsheetObject
- IsStruct
- isThreadInterrupted
- IsUserInAnyRole
- IsUserInRole
- IsUserLoggedIn
- IsValid
- IsValidOauthAccesstoken
- IsWDDX
- IsXML
- IsXmlAttribute
- IsXmlDoc
- IsXmlElem
- IsXmlNode
- IsXmlRoot
- JavaCast
- JSStringFormat
- Functions-l
- LCase
- Left
- Len
- ListAppend
- ListChangeDelims
- ListContains
- ListContainsNoCase
- ListDeleteAt
- ListEach
- ListFilter
- ListFind
- ListFindNoCase
- ListFirst
- ListGetAt
- ListGetDuplicates
- ListInsertAt
- ListLast
- ListLen
- ListMap
- ListPrepend
- ListQualify
- ListReduce
- ListRemoveDuplicates
- ListRest
- ListSetAt
- ListSort
- ListToArray
- ListValueCount
- ListValueCountNoCase
- LJustify
- Location
- Log
- Log10
- LSCurrencyFormat
- LSDateFormat
- LSDateTimeFormat
- LSEuroCurrencyFormat
- LSIsCurrency
- LSIsDate
- LSIsNumeric
- LSNumberFormat
- LSParseCurrency
- LSParseDateTime
- LSParseEuroCurrency
- LSParseNumber
- LSTimeFormat
- LTrim
- Functions-m-r
- Max
- Mid
- Min
- Minute
- Month
- MonthAsString
- Now
- NumberFormat
- ObjectEquals
- ObjectLoad
- ObjectSave
- OnWSAuthenticate
- ORMClearSession
- ORMCloseAllSessions
- ORMCloseSession
- ORMEvictCollection
- ORMEvictEntity
- ORMEvictQueries
- ORMExecuteQuery
- ORMFlush
- ORMFlushall
- ORMGetSession
- ORMGetSessionFactory
- ORMIndex
- ORMIndexPurge
- ORMReload
- ORMSearch
- ORMSearchOffline
- ParagraphFormat
- ParameterExists
- ParseDateTime
- Pi
- PrecisionEvaluate
- ProcessSAMLResponse
- ProcessSAMLLogoutRequest
- Quarter
- PreserveSingleQuotes
- QueryAddColumn
- QueryAddRow
- QueryConvertForGrid
- QueryExecute
- QueryFilter
- QueryGetResult
- QueryGetRow
- QueryKeyExists
- QueryMap
- QueryNew
- QueryReduce
- QuerySetCell
- QuotedValueList
- QueryEach
- Rand
- Randomize
- RandRange
- ReEscape
- REFind
- REFindNoCase
- ReleaseComObject
- REMatch
- REMatchNoCase
- RemoveCachedQuery
- RemoveChars
- RepeatString
- Replace
- ReplaceList
- ReplaceNoCase
- REReplace
- REReplaceNoCase
- RestDeleteApplication
- RestSetResponse
- RestInitApplication
- Reverse
- Right
- RJustify
- Round
- RTrim
- Functions-s
- Second
- SendGatewayMessage
- SendSAMLLogoutResponse
- Serialize
- SerializeJSON
- SerializeXML
- SessionInvalidate
- SessionRotate
- SessionGetMetaData
- SessionInvalidate
- SessionRotate
- SetDay
- SetEncoding
- SetHour
- SetLocale
- SetMonth
- SetProfileString
- SetPropertyString
- SetVariable
- SetYear
- Sgn
- Sin
- Sleep
- SpanExcluding
- SpanIncluding
- SpreadsheetAddAutoFilter
- SpreadsheetAddColumn
- SpreadsheetAddFreezePane
- SpreadsheetAddImage
- SpreadsheetAddInfo
- SpreadsheetAddPageBreaks
- SpreadsheetAddRow
- SpreadsheetAddRows
- SpreadsheetAddSplitPane
- SpreadsheetCreateSheet
- SpreadsheetDeleteColumn
- SpreadsheetDeleteColumns
- SpreadsheetDeleteRow
- SpreadsheetDeleteRows
- SpreadsheetFormatCell
- SpreadsheetFormatColumn
- SpreadsheetFormatCellRange
- SpreadsheetFormatColumn
- SpreadsheetFormatColumns
- SpreadsheetFormatRow
- SpreadsheetFormatRows
- SpreadsheetGetCellComment
- SpreadsheetGetCellFormula
- SpreadsheetGetCellValue
- SpreadsheetGetColumnCount
- SpreadsheetInfo
- SpreadsheetMergeCells
- SpreadsheetNew
- SpreadsheetRead
- SpreadsheetReadBinary
- SpreadsheetRemoveSheet
- SpreadsheetSetActiveSheet
- SpreadsheetSetActiveSheetNumber
- SpreadsheetSetCellComment
- SpreadsheetSetCellFormula
- SpreadsheetSetCellValue
- SpreadsheetSetColumnWidth
- SpreadsheetSetFooter
- SpreadsheetSetHeader
- SpreadsheetSetRowHeight
- SpreadsheetShiftColumns
- SpreadsheetShiftRows
- SpreadsheetWrite
- StreamingSpreadsheetNew
- StreamingSpreadsheetCleanup
- StreamingSpreadsheetRead
- StreamingSpreadsheetProcess
- SpreadsheetSetFooterImage
- SpreadsheetSetHeaderImage
- SpreadsheetSetFittoPage
- SpreadsheetUngroupColumns
- SpreadsheetGroupColumns
- SpreadsheetUngroupRows
- SpreadsheetGroupRows
- SpreadsheetRemoveColumnBreak
- SpreadsheetSetColumnBreak
- SpreadsheetRemoveRowBreak
- SpreadsheetSetRowBreak
- SpreadsheetRemovePrintGridlines
- SpreadsheetAddPrintGridlines
- SpreadsheetGetColumnWidth
- SpreadsheetSetColumnHidden
- SpreadsheetSetRowHidden
- SpreadsheetisColumnHidden
- SpreadsheetisRowHidden
- SpreadsheetisStreamingXmlFormat
- SpreadsheetisXmlFormat
- SpreadsheetisBinaryFormat
- SpreadsheetRenameSheet
- SpreadsheetRemoveSheetNumber
- SpreadsheetGetLastRowNumber
- SpreadsheetGetPrintOrientation
- Sqr
- StripCR
- StructAppend
- StructClear
- StructCopy
- StructCount
- StructDelete
- StructEach
- StructFilter
- StructFind
- StructFindKey
- StructFindValue
- StructGet
- StructGetMetadata
- StructInsert
- StructIsEmpty
- StructKeyArray
- StructKeyExists
- StructKeyList
- StructMap
- StructNew
- StructReduce
- StructSetMetadata
- StructSort
- StructToSorted
- StructUpdate
- StructValueArray
- StoreSetMetadata
- StoreGetACL
- StoreGetMetadata
- StoreAddACL
- StoreSetACL
- Functions-t-z
- Tan
- ThreadJoin
- ThreadTerminate
- Throw
- TimeFormat
- ToBase64
- ToBinary
- ToScript
- ToString
- Trace
- Transactionandconcurrency
- TransactionCommit
- TransactionRollback
- TransactionSetSavePoint
- Trim
- UCase
- URLDecode
- URLEncodedFormat
- URLSessionFormat
- Val
- ValueList
- VerifyClient
- Week
- Wrap
- WriteDump
- WriteLog
- WriteOutput
- WSGetAllChannels
- WSGetSubscribers
- WSPublish
- WSSendMessage
- XmlChildPos
- XmlElemNew
- XmlFormat
- XmlGetNodeType
- XmlNew
- XmlParse
- XmlSearch
- XmlTransform
- XmlValidate
- Year
- YesNoFormat
- ColdFusion tags
- ColdFusion tag summary
- ColdFusion tags by category
- Application framework tags
- Communications tags
- Database manipulation tags
- Data output tags
- Debugging tags
- Exception handling tags
- Extensibility tags
- File management tags
- Flow-control tags
- Forms tags
- Internet Protocol tags
- Page processing tags
- Security tags
- Variable manipulation tags
- Other tags
- Tags a-b
- Tags c
- cfcache
- cfcalendar
- cfcase
- cfcatch
- cfchart
- cfchart tag in ColdFusion
- Get started with cfchart
- Customize a chart using cfchart
- Advanced cfchart customization options
- Create an area chart in ColdFusion
- Create line charts in ColdFusion
- Create bar charts in ColdFusion
- Create floating bar charts in ColdFusion
- Create histograms in ColdFusion
- Create pie charts in ColdFusion
- Create funnel charts in ColdFusion
- Create pyramid charts in ColdFusion
- Create curve charts in ColdFusion
- Create boxplots in ColdFusion
- Create donut charts in ColdFusion
- Create bubble charts in ColdFusion
- Create scatterplots in ColdFusion
- Create radar charts in ColdFusion
- Other chart types in ColdFusion (Cone, Cylinder, Piano, and Bullet)
- Advanced customization options in cfchart
- cfchartdata
- cfchartseries
- cfchartset
- cfclient
- cfclientsettings
- cfcol
- cfcollection
- cfcomponent
- cfcontent
- cfcontinue
- cfcookie
- Tags f
- cffeed
- cffile
- cffile action = "append"
- cffile action = "copy"
- cffile action = "delete"
- cffile action = "move"
- cffile action = "read"
- cffile action = "readBinary"
- cffile action = "rename"
- cffile action = "upload"
- cffile action = "uploadAll"
- cffile action = "write"
- cffileupload
- cffinally
- cfflush
- cfform
- cfformgroup
- cfformitem
- cfftp
- cfftp: Connection: file and directory operations
- cfftp: Opening and closing FTP server connections
- cfftp : Opening and closing secure FTP server connections
- cfftp action = "listDir"
- cffunction
- Tags g-h
- Tags i
- Tags j-l
- cfjava
- cflayout
- cflayoutarea
- cfldap
- cflocation
- cflock
- cflog
- cflogin
- cfloginuser
- cflogout
- cfloop
- cfloop : conditional loop
- cfloop : index loop
- cfloop : looping over a COM collection or structure
- cfloop : looping over a date or time range
- cfloop : looping over a list, a file, or an array
- cfloop : looping over a query
- Tags m-o
- cfmail
- cfmailparam
- cfmailpart
- cfmap
- cfmapitem
- cfmediaplayer
- cfmenu
- cfmenuitem
- cfmessagebox
- cfmodule
- cfNTauthenticate
- cfoauth
- cfobject
- cfobject: .NET object
- cfobject: COM object
- cfobject: component object
- cfobject: CORBA object
- cfobject: Java or EJB object
- cfobject: web service object
- cfobjectcache
- cfoutput
- Tags p-q
- Tags r-s
- Tags t
- Tags u-z
- CFML Reference
- Reserved words and variables
- Ajax JavaScript functions
- Ajax JavaScript functions
- Function summary Ajax
- ColdFusion.Ajax.submitForm
- ColdFusion.Autosuggest.getAutosuggestObject
- ColdFusion.Layout.enableSourceBind
- ColdFusion.MessageBox.getMessageBoxObject
- ColdFusion.ProgressBar.getProgressBarObject
- ColdFusion.MessageBox.isMessageBoxDefined
- JavaScriptFunctionsinColdFusion9Update1
- ColdFusion ActionScript functions
- ColdFusion mobile functions
- Application.cfc reference
- Script functions implemented as CFCs
- ColdFusion Flash Form style reference
- Styles valid for all controls
- Styles for cfform
- Styles for cfformgroup with horizontal or vertical type attributes
- Styles for box-style cfformgroup elements
- Styles for cfformgroup with accordion type attribute
- Styles for cfformgroup with tabnavigator type attribute
- Styles for cfformitem with hrule or vrule type attributes
- Styles for cfinput with radio, checkbox, button, image, or submit type attributes
- Styles for cftextarea tag and cfinput with text, password, or hidden type attributes
- Styles for cfselect with size attribute value of 1
- Styles for cfselect with size attribute value greater than 1
- Styles for cfcalendar tag and cfinput with dateField type attribute
- Styles for the cfgrid tag
- Styles for the cftree tag
- ColdFusion Flash Form Style Reference
- ColdFusion event gateway reference
- ColdFusion Event Gateway reference
- addEvent
- CFEvent
- CFEventclass
- Constructor
- Gateway development interfaces and classes
- getStatus
- setCFCPath
- setCFCMethod
- getOriginatorID
- getLogger
- getBuddyList
- getBuddyInfo
- IM gateway message sending commands
- IM Gateway GatewayHelper class methods
- onIncomingMessage
- onIMServerMessage
- onBuddyStatus
- onAddBuddyResponse
- onAddBuddyRequest
- IM Gateway CFC incoming message methods
- IM gateway methods and commands
- CFML CFEvent structure
- warn
- info
- setOriginatorID
- data command
- submit Multi command
- submit command
- setGatewayType
- setGatewayID
- setData
- setCFCListeners
- outgoingMessage
- getStatusTimeStamp
- numberOfMessagesReceived
- numberOfMessagesSent
- removeBuddy
- removeDeny
- removePermit
- setNickName
- setPermitMode
- setStatus
- SMS Gateway CFEvent structure and commands
- SMS Gateway incoming message CFEvent structure
- getStatusAsString
- getProtocolName
- getPermitMode
- getPermitList
- getNickName
- getName
- getDenyList
- getCustomAwayMessage
- getQueueSize
- getMaxQueueSize
- getHelper
- getGatewayType
- getGatewayServices
- getGatewayID_1
- getGatewayID
- getData
- getCFCTimeout
- setCFCTimeout
- getCFCPath
- getCFCMethod
- GatewayServices class
- Gateway interface
- GatewayHelper interface
- addPermit
- addDeny
- addBuddy
- error
- debug
- Logger class
- stop
- start
- CFML event gateway SendGatewayMessage data parameter
- restart
- fatal
- SMS gateway message sending commands
- ColdFusion C++ CFX Reference
- ColdFusion Java CFX reference
- WDDX JavaScript Objects
- Cloud services
- ColdFusion and GCP Storage
- ColdFusion and GCP Firestore
- ColdFusion and GCP PubSub
- ColdFusion and Amazon S3
- ColdFusion and DynamoDB
- ColdFusion and Amazon SQS
- ColdFusion and Amazon SNS
- ColdFusion and MongoDB
- ColdFusion and Azure Blob
- ColdFusion and Azure Service Bus
- Multi-cloud storage services
- Multi-cloud RDS databases
- ColdFusion and Azure Cosmos DB
Description
Writes a text file on the server, based on dynamic content. You can create static HTML files from the content, or log actions in a text file.
Syntax
<cffile action = "write" file = "full pathname" output = "content" addNewLine = "yes|no" attributes = "file attributes list" charset = "character set option" fixnewline = "yes|no" mode = "permission">
Note: You can specify this tag's attributes in an attributeCollection attribute whose value is a structure. Specify the structure name in the attributeCollection attribute and use the tag's attribute names as structure keys. |
See also
History
See the History section of the main cffile tag page.
Attributes
Attribute |
Req/Opt |
Default |
Description |
|---|---|---|---|
action |
Required |
|
Type of file manipulation that the tag performs. |
file |
Required |
|
Pathname of the file to write. If not an absolute path (starting with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function. |
output |
Required |
|
Content of the file to be created. |
addNewLine |
Optional |
yes |
|
attributes |
Optional |
|
Applies to Windows. A comma-delimited list of attributes to set on the file.
|
charset |
Optional |
JVM default file character set |
The character encoding in which the file contents is encoded. The following list includes commonly used values:
|
fixnewline |
Optional |
no |
|
mode |
Optional |
|
Applies only to UNIX and Linux. Permissions. Octal values of UNIX chmod command. Assigned to owner, group, and other, respectively; for example:
|
Example
This example creates a file with information a user entered in an HTML insert form:
<cffile action = "write" file = "c:\files\updates\#Form.UpdateTitle#.txt" output = "Created By: #Form.FullName# Date: #Form.Date# #Form.Content#">
If the user submitted a form with the following:
UpdateTitle = "FieldWork" FullName = "World B. Frueh" Date = "10/30/01" Content = "We had a wonderful time in Cambridgeport."
ColdFusion would create a file named FieldWork.txt in the c:\files\updates\ directory and the file would contain the following text:
Created By: World B. Frueh Date: 10/30/01 We had a wonderful time in Cambridgeport.
This example shows the use of the mode attribute for UNIX. It creates the file /tmp/foo with permissions rw-r-r- (owner = read/write, group = read, other = read):
<cffile action = "write" file = "/tmp/foo" mode = 644>
This example appends to the file and sets permissions to read/write (rw) for all:
<cffile action = "append" destination = "/home/tomj/testing.txt" mode = 666 output = "Is this a test?">
This example uploads a file and gives it the permissions owner/group/other = read/write/execute):
cffile action = "upload" fileField = "fieldname" destination = "/tmp/program.exe" mode = 777>
This example uses the fixnewline attribute to changes embedded line-ending characters in xmlString, which is derived from xmlData, to operating-system specific line endings.
<cfxml variable="xmlData"> <docroot> <payload type="string">This is some plain text</payload> </docroot> </cfxml> <cfset xmlString = toString(xmlData)> <cfset key = createUUID()> <cfset encString=encrypt(xmlString, key)> <cffile action="write" addnewline="yes" file="C:\ColdFusion9\wwwroot\test\store.dat" output="#encString#" fixnewline="yes"> <cffile action="read" file="C:\ColdFusion9\wwwroot\test\store.dat" variable="retrievedString"> <cfset decString=decrypt(retrievedString, key)> <cfdump var="#decString#"> <cfset newXML = xmlParse(decString)> <cfdump var="#newXML#">
ColdFusion supports using cffile to write an image, for example:
<!--- Create a new cfimage. --->
<cfset myImage=ImageNew("",200,200)>
<!--- Draw a square on the image. --->
<cfset ImageDrawRect(myImage,10,10,100,100)>
<!--- Use cffile to write the cfimage to a JPG. --->
<cffile action="write" output="#myImage#" file="c:\cfpix\square.jpg">
Real-world uses of cffile action="write"
Automated daily sales report generation
A retail management system needs to generate daily sales summary reports in CSV format for accounting department review and archival purposes.
Problem statement
The accounting team requires end-of-day sales reports that include transaction summaries, total revenue, and tax calculations. These reports must be saved as CSV files to a network shared folder where they can be imported into the accounting software. Manual report generation is time-consuming and error-prone, and the data needs to be formatted consistently for automated import processes.
<cfquery name="qDailySales" datasource="retailDB">
SELECT
transaction_date,
product_id,
product_name,
quantity,
unit_price,
total_amount,
tax_amount
FROM sales_transactions
WHERE CAST(transaction_date AS DATE) = CAST(GETDATE() AS DATE)
ORDER BY transaction_date
</cfquery>
<cfset reportContent = "Date,Product ID,Product Name,Quantity,Unit Price,Total,Tax#Chr(13)#Chr(10)#">
<cfloop query="qDailySales">
<cfset reportContent &= "#DateFormat(transaction_date, 'yyyy-mm-dd')#,">
<cfset reportContent &= "#product_id#,">
<cfset reportContent &= '"#product_name#",'>
<cfset reportContent &= "#quantity#,">
<cfset reportContent &= "#NumberFormat(unit_price, '9.99')#,">
<cfset reportContent &= "#NumberFormat(total_amount, '9.99')#,">
<cfset reportContent &= "#NumberFormat(tax_amount, '9.99')##Chr(13)#Chr(10)#">
</cfloop>
<cfset fileName = "sales_report_#DateFormat(Now(), 'yyyymmdd')#.csv">
<cfset filePath = "\\network\shared\accounting\daily_reports\#fileName#">
<cffile action="write"
file="#filePath#"
output="#reportContent#"
charset="utf-8"
mode="644">
<cflog text="Daily sales report generated: #fileName#" type="information">
Custom application error logging system
An enterprise web application needs a centralized error logging mechanism that writes detailed error information to dated log files for debugging and compliance auditing.
Problem statement
<cffunction name="logApplicationError" access="public" returntype="void">
<cfargument name="errorStruct" type="struct" required="true">
<cfargument name="userContext" type="struct" required="false" default="#StructNew()#">
<cfset var logDirectory = ExpandPath("/logs/application_errors")>
<cfset var logFileName = "error_log_#DateFormat(Now(), 'yyyy-mm-dd')#.log">
<cfset var logFilePath = "#logDirectory#/#logFileName#">
<!--- Ensure directory exists --->
<cfif NOT DirectoryExists(logDirectory)>
<cfdirectory action="create" directory="#logDirectory#">
</cfif>
<!--- Build detailed error log entry --->
<cfset var logEntry = "">
<cfset logEntry &= "========================================#Chr(13)#Chr(10)#">
<cfset logEntry &= "Timestamp: #DateFormat(Now(), 'yyyy-mm-dd')# #TimeFormat(Now(), 'HH:mm:ss')##Chr(13)#Chr(10)#">
<cfset logEntry &= "Error Type: #arguments.errorStruct.type#" & Chr(13) & Chr(10)>
<cfset logEntry &= "Error Message: #arguments.errorStruct.message#" & Chr(13) & Chr(10)>
<cfset logEntry &= "Error Detail: #arguments.errorStruct.detail#" & Chr(13) & Chr(10)>
<cfif StructKeyExists(arguments.userContext, "userID")>
<cfset logEntry &= "User ID: #arguments.userContext.userID#" & Chr(13) & Chr(10)>
</cfif>
<cfif StructKeyExists(arguments.userContext, "sessionID")>
<cfset logEntry &= "Session ID: #arguments.userContext.sessionID#" & Chr(13) & Chr(10)>
</cfif>
<cfset logEntry &= "Request URL: #CGI.SCRIPT_NAME#?#CGI.QUERY_STRING#" & Chr(13) & Chr(10)>
<cfset logEntry &= "Remote IP: #CGI.REMOTE_ADDR#" & Chr(13) & Chr(10)>
<cfset logEntry &= "User Agent: #CGI.HTTP_USER_AGENT#" & Chr(13) & Chr(10)>
<cfset logEntry &= "========================================" & Chr(13) & Chr(10) & Chr(13) & Chr(10)>
<!--- Append to log file --->
<cffile action="write"
file="#logFilePath#"
output="#logEntry#"
addnewline="no"
charset="utf-8"
mode="644">
</cffunction>
Dynamic configuration file management
A multi-tenant SaaS application needs to dynamically generate and update customer-specific configuration files when clients modify their settings through the admin panel.
Problem statement
Each customer tenant requires custom configuration settings (API keys, feature flags, branding options) that must be persisted to JSON configuration files. These files are read by various application modules at runtime. When administrators update settings via the web interface, the configuration files must be immediately updated without requiring application restarts. The system needs to maintain configuration versioning for rollback capabilities.
<cffunction name="updateTenantConfiguration" access="public" returntype="boolean">
<cfargument name="tenantID" type="numeric" required="true">
<cfargument name="configSettings" type="struct" required="true">
<cfset var configDir = ExpandPath("/config/tenants")>
<cfset var configFile = "#configDir#/tenant_#arguments.tenantID#_config.json">
<cfset var backupFile = "#configDir#/tenant_#arguments.tenantID#_config_backup_#DateFormat(Now(),'yyyymmdd')#_#TimeFormat(Now(),'HHmmss')#.json">
<cftry>
<!--- Backup existing configuration --->
<cfif FileExists(configFile)>
<cffile action="copy"
source="#configFile#"
destination="#backupFile#">
</cfif>
<!--- Prepare configuration structure --->
<cfset var configOutput = {
"tenantID" = arguments.tenantID,
"lastUpdated" = DateFormat(Now(), "yyyy-mm-dd") & " " & TimeFormat(Now(), "HH:mm:ss"),
"apiEndpoint" = arguments.configSettings.apiEndpoint,
"apiKey" = arguments.configSettings.apiKey,
"features" = {
"advancedReporting" = arguments.configSettings.advancedReporting,
"customBranding" = arguments.configSettings.customBranding,
"ssoEnabled" = arguments.configSettings.ssoEnabled
},
"branding" = {
"companyName" = arguments.configSettings.companyName,
"logoURL" = arguments.configSettings.logoURL,
"primaryColor" = arguments.configSettings.primaryColor
},
"limits" = {
"maxUsers" = arguments.configSettings.maxUsers,
"maxStorage" = arguments.configSettings.maxStorage
}
}>
<!--- Convert to JSON and write to file --->
<cfset var jsonConfig = SerializeJSON(configOutput)>
<cffile action="write"
file="#configFile#"
output="#jsonConfig#"
charset="utf-8"
mode="644">
<!--- Log the configuration update --->
<cflog text="Configuration updated for tenant #arguments.tenantID#"
type="information"
file="tenant_config">
<cfreturn true>
<cfcatch type="any">
<cflog text="Failed to update configuration for tenant #arguments.tenantID#: #cfcatch.message#"
type="error"
file="tenant_config">
<cfreturn false>
</cfcatch>
</cftry>
</cffunction>
Export customer data for GDPR compliance
A customer relationship management (CRM) system needs to provide customers with a complete export of their personal data in a human-readable format to comply with GDPR data portability requirements.
Problem statement
Under GDPR regulations, customers have the right to receive all their personal data held by the company in a structured, commonly used, and machine-readable format. The system must generate comprehensive data exports that include customer profiles, communication history, purchase records, and preferences. These exports must be generated on-demand, secured, and available for download within 30 days.
<cffunction name="generateGDPRDataExport" access="public" returntype="string">
<cfargument name="customerID" type="numeric" required="true">
<cfset var exportDir = ExpandPath("/secure_exports/gdpr")>
<cfset var exportFileName = "customer_data_export_#arguments.customerID#_#CreateUUID()#.txt">
<cfset var exportFilePath = "#exportDir#/#exportFileName#">
<!--- Ensure directory exists --->
<cfif NOT DirectoryExists(exportDir)>
<cfdirectory action="create" directory="#exportDir#">
</cfif>
<!--- Retrieve customer data from database --->
<cfquery name="qCustomer" datasource="crmDB">
SELECT * FROM customers WHERE customer_id = <cfqueryparam value="#arguments.customerID#" cfsqltype="cf_sql_integer">
</cfquery>
<cfquery name="qOrders" datasource="crmDB">
SELECT * FROM orders WHERE customer_id = <cfqueryparam value="#arguments.customerID#" cfsqltype="cf_sql_integer">
</cfquery>
<cfquery name="qCommunications" datasource="crmDB">
SELECT * FROM communications WHERE customer_id = <cfqueryparam value="#arguments.customerID#" cfsqltype="cf_sql_integer">
</cfquery>
<!--- Build export content --->
<cfset var exportContent = "">
<cfset exportContent &= "GDPR DATA EXPORT REPORT" & Chr(13) & Chr(10)>
<cfset exportContent &= "Generated: #DateFormat(Now(), 'yyyy-mm-dd')# #TimeFormat(Now(), 'HH:mm:ss')#" & Chr(13) & Chr(10)>
<cfset exportContent &= "Customer ID: #arguments.customerID#" & Chr(13) & Chr(10)>
<cfset exportContent &= String(80, "=") & Chr(13) & Chr(10) & Chr(13) & Chr(10)>
<!--- Personal Information --->
<cfset exportContent &= "PERSONAL INFORMATION" & Chr(13) & Chr(10)>
<cfset exportContent &= String(40, "-") & Chr(13) & Chr(10)>
<cfloop query="qCustomer">
<cfset exportContent &= "Name: #first_name# #last_name#" & Chr(13) & Chr(10)>
<cfset exportContent &= "Email: #email#" & Chr(13) & Chr(10)>
<cfset exportContent &= "Phone: #phone#" & Chr(13) & Chr(10)>
<cfset exportContent &= "Address: #address#, #city#, #state# #zip#" & Chr(13) & Chr(10)>
<cfset exportContent &= "Account Created: #DateFormat(created_date, 'yyyy-mm-dd')#" & Chr(13) & Chr(10)>
</cfloop>
<cfset exportContent &= Chr(13) & Chr(10)>
<!--- Order History --->
<cfset exportContent &= "ORDER HISTORY" & Chr(13) & Chr(10)>
<cfset exportContent &= String(40, "-") & Chr(13) & Chr(10)>
<cfloop query="qOrders">
<cfset exportContent &= "Order ##: #order_id#" & Chr(13) & Chr(10)>
<cfset exportContent &= "Date: #DateFormat(order_date, 'yyyy-mm-dd')#" & Chr(13) & Chr(10)>
<cfset exportContent &= "Amount: $#NumberFormat(total_amount, '9.99')#" & Chr(13) & Chr(10)>
<cfset exportContent &= "Status: #status#" & Chr(13) & Chr(10) & Chr(13) & Chr(10)>
</cfloop>
<!--- Communication History --->
<cfset exportContent &= "COMMUNICATION HISTORY" & Chr(13) & Chr(10)>
<cfset exportContent &= String(40, "-") & Chr(13) & Chr(10)>
<cfloop query="qCommunications">
<cfset exportContent &= "Date: #DateFormat(comm_date, 'yyyy-mm-dd')#" & Chr(13) & Chr(10)>
<cfset exportContent &= "Type: #comm_type#" & Chr(13) & Chr(10)>
<cfset exportContent &= "Subject: #subject#" & Chr(13) & Chr(10)>
<cfset exportContent &= "Content: #content#" & Chr(13) & Chr(10) & Chr(13) & Chr(10)>
</cfloop>
<!--- Write to file --->
<cffile action="write"
file="#exportFilePath#"
output="#exportContent#"
charset="utf-8"
mode="600">
<!--- Log the export request --->
<cflog text="GDPR data export generated for customer #arguments.customerID#"
type="information"
file="gdpr_exports">
<cfreturn exportFileName>
</cffunction>