- 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
Does either or both of the following:
- Sets the MIME content encoding header for the current page; if the encoding information includes a character encoding, sets the character encoding of generated output.
- Sends the contents of a file, or of a variable that contains binary data, as the page output.
To restrict this tag, use the settings in the ColdFusion Administrator > Security > Sandbox Security. For more information, see the Administrator online Help.
Category
Syntax
<cfcontent deleteFile = "yes|no" file = "filename" reset = "yes|no" type = "file type" variable = "variable name">
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
cfcol, cfheader, cfhttp, cfoutput, cftable
History
ColdFusion 8: Changed the behavior of the tag if the type attribute is not specified and the file attribute is specified. Previously, ColdFusion assumed a default file type of text/html. Now, ColdFusion attempts to get the content type from the file.ColdFusion MX 7: Added the variable attribute.
Attributes
Attribute |
Req/Opt |
Default |
Description |
|
|---|---|---|---|---|
deleteFile |
Optional |
no |
Applies only if you specify a file with the file attribute.
|
|
file |
Optional |
|
Name of an on-disk or in-memory file whose contents provide the page output. The filename must start with a drive letter and a colon, or a forward or backward slash. When using ColdFusion in a distributed configuration, the file attribute must refer to a path on the system on which the web server runs. When you use this attribute, any other output on the current CFML page is ignored; only the contents of the file are sent to the client. |
|
reset |
Optional |
yes |
If you specify a file or variable attribute, this attribute has no effect; otherwise, it does the following:
|
|
type |
Optional |
|
The MIME content type of the page, optionally followed by a semicolon and the character encoding. By default, ColdFusion sends pages as text/html content type in the UTF-8 character encoding. However, if the file attribute is specified, ColdFusion attempts to get the content type from the file.
|
|
variable |
Optional |
|
Name of a ColdFusion binary variable whose contents can be displayed by the browser, such as the contents of a chart generated by the cfchart tag or a PDF or Excel file retrieved by a cffile action="readBinary" tag. When you use this attribute, any other output on the current CFML page is ignored; only the contents of the file are sent to the client. |
Usage
To set the character encoding (character set) of generated output, including the page HTML, use code such as the following:
<cfcontent type="text/html; charset=ISO-8859-1"> |
When ColdFusion processes an HTTP request, it determines the character encoding to use for the data it returns in the HTTP response. By default, ColdFusion returns character data using the Unicode UTF-8 format, regardless of the value of an HTML meta tag in the page. You can use the cfcontent tag to override the default character encoding of the response. For example, to tell ColdFusion to return the page using Japanese EUC character encoding, use the type attribute, as follows:
<cfcontent type="text/html; charset=EUC-JP"> |
If you call the cfcontent tag from a custom tag, and you do not want the tag to discard the current page when it is called from another application or custom tag, set reset = "no".
If a file delete operation is unsuccessful, ColdFusion throws an error.Do not use this tag after the cfflush tag on a page, it has no effect or ColdFusion throws an error. The following tag can force most browsers to display a dialog box that asks users whether they want to save the contents of the file specified by the cfcontent tag using the filename specified by the filename value. If the user selects to open the file, most browsers open the file in the related application, not the browser window.
<cfheader name="Content-Disposition" value="attachment; filename=filename.ext"> |
Some file types, such as PDF documents, do not use executable code and can display directly in most browsers. To request the browser to display the file directly, use a cfheader tag similar to the following:
<cfheader name="Content-Disposition" value="inline; filename=name.ext"> |
You can use any value for the filename part of the filename attribute, but the ext part must be the standard Windows extension for the file type. For file types that might contain executable code, such as Microsoft Excel documents, most browsers always ask before opening the document. For these file types, the inline content disposition specification requests the browser to display the file directly if the user selects to open the file.
For more information on character encodings, see the following web pages:
- The page at www.w3.org/International/O-charset.en.html provides general information on character encodings and the web, and has several useful links.
- The page at www.iana.org/assignments/character-sets is a complete list of character sets names used on the Internet, maintained by the Internet Assigned Numbers Authority.
ColdFusion uses the Java JCE for encoding support. The page at http://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html lists the character encodings that JCE 6, and therefore ColdFusion, can interpret. This list uses Java internal names, not the IANA character encoding names that you use in the SetEncoding charset parameter and other ColdFusion attributes and parameters.
For a complete list of media types used on the Internet, see www.iana.org/assignments/media-types/.When using cfabort, cflocation, or cfcontent tags, the OnAbort method is invoked instead on OnRequestEnd.
Example
<!--- CFCONTENT Example 1
This example shows the use of cfcontent to return the contents of the CF
Documentation page dynamically to the browser. You might need to change the
path and/or drive letter depending on how ColdFusion is installed on your
system. Notice that the graphics do not display and the hyperlinks do not work,
because the html page uses relative filename references.
The root of the reference is the ColdFusion page, not the location of the
html page. --->
<cfcontent type = "text/html"
file = "C:\ColdFusion9\wwwroot\cfdocs\dochome.htm"
deleteFile = "no">
<!--- CFCONTENT Example 2
This example shows how the Reset attribute changes text output. Notice how the
first text section ("This example shows how the Reset attribute changes output
for text reset = "Yes":123) does NOT print out to the screen. --->
<p>This example shows how the Reset attribute changes output for text.</p>
<p>reset = "Yes": 123 <BR> <cfcontent type = "text/html" reset = "Yes">456</p>
<p>This example shows how the Reset attribute changes output for text.</p>
<p>reset = "No": 123 <BR> <cfcontent type = "text/html" reset = "No">456</p>
<!--- CFCONTENT Example 3
This example triggers a download of an Excel file. The user is prompted with an option to save the file or open it in the browser. --->
<cfheader name="Content-Disposition" value="inline; filename=acmesales03.xls">
<cfcontent type="application/vnd.ms-excel" file="c:\temp\acmesales03.xls">
<!--- CFCONTENT Example 4
This example triggers a download of a Word document then deletes the original from the "temp" directory. The user is prompted with an option to save the file or open it in the browser. --->
<cfheader name="Content-Disposition" value="inline; filename=temp.doc">
<cfcontent type="application/msword" file="c:\temp\Cable.doc" deletefile="yes">
<!--- CFCONTENT Example 5
This example causes the browser to treat the HTML table as Excel data.
Excel interprets the table format.
Because Excel can include executable code, the browser prompts the user whether
to save the file or open it in a browser. --->
<cfheader name="Content-Disposition" value="inline; filename=acmesalesQ1.xls">
<cfcontent type="application/vnd.msexcel">
<table border="2">
<tr><td>Month</td><td>Quantity</td><td>$ Sales</td></tr>
<tr><td>January</td><td>80</td><td >$245</td></tr>
<tr><td>February</td><td>100</td><td>$699</td></tr>
<tr><td>March</td><td>230</td><td >$2036</td></tr>
<tr><td>Total</td><td>=Sum(B2..B4)</td><td>=Sum(C2..C4)</td></tr>
</table>
Real-world uses of the cfcontent tag
Secure document download system
Enterprise organizations need to provide secure access to confidential documents such as employee contracts, financial reports, and legal agreements. Users must be able to download these documents only after authentication and authorization checks, with complete audit logging of who accessed what documents and when.
Problem statement
- Direct file links expose confidential documents to unauthorized access via URL manipulation
- No way to track who downloaded which documents and when for compliance audits
- File paths revealed in URLs create security vulnerabilities and information disclosure
- Cannot enforce document access policies or permissions at download time
- Inability to set proper filenames causes confusion when users save generic-named files
Solution
The cfcontent tag implements a secure document delivery system that validates user permissions before serving files, uses cfcontent to deliver documents stored outside the publicly accessible web root, sets user-friendly filenames via Content-Disposition headers, and logs all download activity with timestamps and user information for complete audit trails.
<cfset documentLibrary = {
"EMP001" = {name = "Employment_Contract_2024.pdf", type = "application/pdf", size = "245 KB"},
"FIN002" = {name = "Q4_Financial_Report.pdf", type = "application/pdf", size = "1.2 MB"},
"POL003" = {name = "Company_Policy_Handbook.pdf", type = "application/pdf", size = "890 KB"},
"INV004" = {name = "Annual_Invoice_Summary.xlsx", type = "application/vnd.ms-excel", size = "156 KB"}
}>
<!--- Simulated user session --->
<cfset session.userId = "USER" & randRange(1000, 9999)>
<cfset session.userName = "John Doe">
<cfset session.userRole = "Employee">
<cfset session.isAuthenticated = true>
<!--- Download audit log --->
<cfset downloadLog = []>
<!--- Handle download request --->
<cfif structKeyExists(url, "docId") AND structKeyExists(url, "action") AND url.action EQ "download">
<cftry>
<!--- Security: Verify authentication --->
<cfif NOT session.isAuthenticated>
<cfheader statuscode="401">
<cfoutput>
<h1>Access Denied</h1>
<p>You must be logged in to download documents.</p>
</cfoutput>
<cfabort>
</cfif>
<!--- Validate document ID --->
<cfif NOT structKeyExists(documentLibrary, url.docId)>
<cfheader statuscode="404">
<cfoutput>
<h1>Document Not Found</h1>
<p>The requested document does not exist.</p>
</cfoutput>
<cfabort>
</cfif>
<!--- Get document info --->
<cfset doc = documentLibrary[url.docId]>
<!--- Log download attempt --->
<cfset auditEntry = {
timestamp = now(),
userId = session.userId,
userName = session.userName,
documentId = url.docId,
documentName = doc.name,
ipAddress = "192.168.1.100",
status = "SUCCESS"
}>
<cfset arrayAppend(downloadLog, auditEntry)>
<!--- For CFFiddle demo: Simulate file download with message --->
<!--- In production, this would serve the actual file:
<cfheader name="Content-Disposition" value="attachment; filename=#doc.name#">
<cfcontent type="#doc.type#" file="c:\secure_docs\#doc.name#">
--->
<!--- CFFiddle-compatible demonstration --->
<cfheader name="Content-Disposition" value="attachment; filename=#doc.name#">
<cfcontent type="text/plain" reset="yes">
<cfoutput>
Document Download Simulated
===========================
Document: #doc.name#
Type: #doc.type#
Size: #doc.size#
Downloaded by: #session.userName# (ID: #session.userId#)
Download Time: #dateTimeFormat(now(), "yyyy-mm-dd HH:nn:ss")#
In production, this would deliver the actual file content.
The file would be served from a secure location outside the web root.
Audit Trail:
- User authenticated: YES
- Permission verified: YES
- Download logged: YES
- IP Address: #auditEntry.ipAddress#
</cfoutput>
<cfabort>
<cfcatch type="any">
<!--- Log error --->
<cfset errorEntry = {
timestamp = now(),
userId = session.userId,
documentId = url.docId,
error = cfcatch.message,
status = "FAILED"
}>
<cfset arrayAppend(downloadLog, errorEntry)>
<cfheader statuscode="500">
<cfoutput>
<h1>Download Error</h1>
<p>An error occurred while processing your download request.</p>
<p>Error: #cfcatch.message#</p>
</cfoutput>
<cfabort>
</cfcatch>
</cftry>
</cfif>
<!DOCTYPE html>
<html>
<head>
<title>Secure Document Library</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh; padding: 20px; }
.container { max-width: 900px; margin: 0 auto; }
.header { background: white; padding: 30px; border-radius: 15px 15px 0 0;
box-shadow: 0 -5px 20px rgba(0,0,0,0.1); }
.header h1 { color: #2c3e50; margin-bottom: 10px; }
.user-info { display: flex; align-items: center; gap: 15px; padding: 15px;
background: #f8f9fa; border-radius: 8px; margin-top: 15px; }
.user-avatar { width: 50px; height: 50px; border-radius: 50%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
display: flex; align-items: center; justify-content: center;
color: white; font-size: 24px; font-weight: bold; }
.document-list { background: white; padding: 30px; border-radius: 0 0 15px 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2); }
.doc-item { display: flex; align-items: center; justify-content: space-between;
padding: 20px; background: #f8f9fa; border-radius: 10px;
margin-bottom: 15px; border-left: 4px solid #667eea;
transition: all 0.3s; }
.doc-item:hover { transform: translateX(5px); box-shadow: 0 5px 15px rgba(102,126,234,0.3); }
.doc-icon { font-size: 36px; margin-right: 15px; }
.doc-info { flex: 1; }
.doc-name { font-weight: bold; color: #2c3e50; margin-bottom: 5px; }
.doc-meta { font-size: 13px; color: #7f8c8d; }
.download-btn { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white; padding: 12px 24px; border: none; border-radius: 8px;
cursor: pointer; font-weight: bold; text-decoration: none;
display: inline-block; transition: all 0.3s; }
.download-btn:hover { transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102,126,234,0.4); }
.security-notice { background: #fff3cd; padding: 15px; border-radius: 8px;
border-left: 4px solid #ffc107; margin-bottom: 20px; }
.audit-log { margin-top: 30px; background: #f8f9fa; padding: 20px;
border-radius: 10px; }
.audit-log h3 { color: #2c3e50; margin-bottom: 15px; }
.audit-entry { padding: 10px; background: white; border-radius: 5px;
margin-bottom: 10px; font-size: 14px; }
.badge { display: inline-block; padding: 4px 10px; border-radius: 12px;
font-size: 11px; font-weight: bold; margin-left: 10px; }
.badge-success { background: #28a745; color: white; }
.badge-role { background: #667eea; color: white; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🔒 Secure Document Library</h1>
<div class="user-info">
<div class="user-avatar">
<cfoutput>#left(session.userName, 1)#</cfoutput>
</div>
<div>
<cfoutput>
<strong>#session.userName#</strong>
<span class="badge badge-role">#session.userRole#</span><br>
<small style="color: ##7f8c8d;">User ID: #session.userId#</small>
</cfoutput>
</div>
<cfif session.isAuthenticated>
<span class="badge badge-success" style="margin-left: auto;">✓ AUTHENTICATED</span>
</cfif>
</div>
</div>
<div class="document-list">
<div class="security-notice">
<strong>🛡️ Security Notice:</strong> All document downloads are logged and monitored.
Files are served from secure storage outside the web root. Unauthorized access attempts
will be reported.
</div>
<h2 style="color: #2c3e50; margin-bottom: 20px;">Available Documents</h2>
<cfloop collection="#documentLibrary#" item="docId">
<cfset doc = documentLibrary[docId]>
<div class="doc-item">
<div class="doc-icon">
<cfif findNoCase(".pdf", doc.name)>
📄
<cfelseif findNoCase(".xlsx", doc.name) OR findNoCase(".xls", doc.name)>
📊
<cfelse>
📎
</cfif>
</div>
<div class="doc-info">
<div class="doc-name">
<cfoutput>#doc.name#</cfoutput>
</div>
<div class="doc-meta">
<cfoutput>
Document ID: #docId# | Size: #doc.size# | Type: #doc.type#
</cfoutput>
</div>
</div>
<cfoutput>
<a href="?docId=#docId#&action=download" class="download-btn">
⬇ Download
</a>
</cfoutput>
</div>
</cfloop>
<cfif arrayLen(downloadLog) GT 0>
<div class="audit-log">
<h3>📋 Download Audit Log</h3>
<cfloop array="#downloadLog#" index="entry">
<div class="audit-entry">
<cfoutput>
<strong>#dateTimeFormat(entry.timestamp, "yyyy-mm-dd HH:nn:ss")#</strong> -
User: #entry.userName# (#entry.userId#) -
Document: #entry.documentName# (#entry.documentId#) -
<span class="badge badge-success">#entry.status#</span>
<cfif structKeyExists(entry, "ipAddress")>
<br><small>IP: #entry.ipAddress#</small>
</cfif>
<cfif structKeyExists(entry, "error")>
<br><small style="color: ##e74c3c;">Error: #entry.error#</small>
</cfif>
</cfoutput>
</div>
</cfloop>
</div>
</cfif>
</div>
</div>
</body>
</html>
Excel report generator
Sales and analytics teams require the ability to export database reports and dashboard data directly to Excel format for offline analysis, client presentations, and integration with other business intelligence tools. The system must dynamically generate Excel-compatible content from HTML tables with formulas and formatting that Excel can interpret and calculate automatically.
Problem statement
- Manual copy-paste of data from web pages to Excel loses formatting and requires cleanup
- Static CSV exports don't support Excel formulas or calculated fields
- Generating actual Excel binary files requires complex libraries and server resources
- Users need descriptive filenames with dates for organizing exported reports
Solution
The cfcontent tag delivers HTML tables as Excel-readable content by setting the appropriate MIME type (application/vnd.ms-excel) and using Content-Disposition headers to specify meaningful filenames.
<cfset reportData = [
{month = "January", region = "North", units = 1250, revenue = 62500, target = 60000},
{month = "January", region = "South", units = 980, revenue = 49000, target = 45000},
{month = "January", region = "East", units = 1420, revenue = 71000, target = 70000},
{month = "January", region = "West", units = 1100, revenue = 55000, target = 50000},
{month = "February", region = "North", units = 1380, revenue = 69000, target = 60000},
{month = "February", region = "South", units = 1050, revenue = 52500, target = 45000},
{month = "February", region = "East", units = 1560, revenue = 78000, target = 70000},
{month = "February", region = "West", units = 1220, revenue = 61000, target = 50000}
]>
<cfset currentQuarter = "Q1">
<cfset currentYear = year(now())>
<cfset reportDate = dateFormat(now(), "yyyy-mm-dd")>
<!--- Handle export request --->
<cfif structKeyExists(url, "action") AND url.action EQ "export">
<!--- Set Excel-friendly filename --->
<cfset fileName = "Sales_Report_#currentQuarter#_#currentYear#_#reportDate#.xls">
<!--- Configure headers for Excel download --->
<cfheader name="Content-Disposition" value="attachment; filename=#fileName#">
<cfcontent type="application/vnd.ms-excel" reset="yes">
<!--- Generate Excel-compatible HTML table --->
<cfoutput>
<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
table { border-collapse: collapse; font-family: Arial, sans-serif; }
th { background-color: ##4472C4; color: white; font-weight: bold;
padding: 10px; border: 1px solid ##ddd; }
td { padding: 8px; border: 1px solid ##ddd; }
.number { text-align: right; }
.currency { text-align: right; }
.total-row { background-color: ##E7E6E6; font-weight: bold; }
.header-row { background-color: ##F2F2F2; font-weight: bold; }
</style>
</head>
<body>
<h1>Sales Performance Report</h1>
<p><strong>Quarter:</strong> #currentQuarter# #currentYear#</p>
<p><strong>Report Generated:</strong> #dateTimeFormat(now(), "mmmm d, yyyy 'at' h:nn tt")#</p>
<p><strong>Export Date:</strong> #reportDate#</p>
<br>
<table border="1">
<thead>
<tr>
<th>Month</th>
<th>Region</th>
<th>Units Sold</th>
<th>Revenue ($)</th>
<th>Target ($)</th>
<th>vs Target (%)</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<cfset rowNum = 2> <!--- Excel row numbering starts at row 2 after header --->
<cfloop array="#reportData#" index="row">
<cfset rowNum++>
<tr>
<td>#row.month#</td>
<td>#row.region#</td>
<td class="number">#numberFormat(row.units, "999,999")#</td>
<td class="currency">#dollarFormat(row.revenue)#</td>
<td class="currency">#dollarFormat(row.target)#</td>
<!--- Excel Formula: Calculate percentage vs target --->
<td class="number">=ROUND((D#rowNum#/E#rowNum#)*100,1)</td>
<!--- Excel Formula: IF statement for status --->
<td>=IF(D#rowNum#>=E#rowNum#,"✓ Met","✗ Missed")</td>
</tr>
</cfloop>
<!--- Summary Totals Row --->
<tr class="total-row">
<td colspan="2"><strong>TOTAL</strong></td>
<td class="number">=SUM(C3:C#rowNum#)</td>
<td class="currency">=SUM(D3:D#rowNum#)</td>
<td class="currency">=SUM(E3:E#rowNum#)</td>
<td class="number">=ROUND((D#rowNum+1#/E#rowNum+1#)*100,1)</td>
<td>=IF(D#rowNum+1#>=E#rowNum+1#,"✓ ACHIEVED","✗ BELOW TARGET")</td>
</tr>
</tbody>
</table>
<br><br>
<h3>Regional Summary</h3>
<table border="1">
<thead>
<tr class="header-row">
<th>Region</th>
<th>Total Revenue</th>
<th>Avg Monthly Revenue</th>
<th>Performance</th>
</tr>
</thead>
<tbody>
<cfset regions = ["North", "South", "East", "West"]>
<cfloop array="#regions#" index="region">
<tr>
<td>#region#</td>
<!--- Use SUMIF to calculate regional totals --->
<td class="currency">=SUMIF(B3:B#rowNum#,"#region#",D3:D#rowNum#)</td>
<!--- Average formula --->
<td class="currency">=SUMIF(B3:B#rowNum#,"#region#",D3:D#rowNum#)/COUNTIF(B3:B#rowNum#,"#region#")</td>
<!--- Conditional formatting indicator --->
<td>=IF(SUMIF(B3:B#rowNum#,"#region#",D3:D#rowNum#)>120000,"⭐ Excellent",IF(SUMIF(B3:B#rowNum#,"#region#",D3:D#rowNum#)>100000,"👍 Good","📈 Needs Improvement"))</td>
</tr>
</cfloop>
</tbody>
</table>
<br><br>
<p><em>Note: This report contains Excel formulas that will calculate automatically when opened in Microsoft Excel.</em></p>
<p><em>Generated by Sales Analytics System | Confidential - Internal Use Only</em></p>
</body>
</html>
</cfoutput>
<cfabort>
</cfif>
<!DOCTYPE html>
<html>
<head>
<title>Sales Report Export</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Arial', sans-serif; background: #f5f5f5; padding: 20px; }
.container { max-width: 1200px; margin: 0 auto; background: white;
border-radius: 10px; box-shadow: 0 0 20px rgba(0,0,0,0.1); }
.header { background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
color: white; padding: 30px; border-radius: 10px 10px 0 0; }
.header h1 { font-size: 28px; margin-bottom: 10px; }
.content { padding: 30px; }
.stats-grid { display: grid; grid-template-columns: repeat(4, 1fr);
gap: 15px; margin-bottom: 30px; }
.stat-card { background: #f8f9fa; padding: 20px; border-radius: 8px;
text-align: center; border-left: 4px solid #1e3c72; }
.stat-value { font-size: 32px; font-weight: bold; color: #1e3c72; margin: 10px 0; }
.stat-label { color: #6c757d; font-size: 14px; }
table { width: 100%; border-collapse: collapse; margin: 20px 0; }
th { background: #1e3c72; color: white; padding: 12px; text-align: left; }
td { padding: 10px; border-bottom: 1px solid #dee2e6; }
tr:hover { background: #f8f9fa; }
.number { text-align: right; }
.currency { text-align: right; font-weight: 500; }
.status-met { color: #28a745; font-weight: bold; }
.status-missed { color: #dc3545; font-weight: bold; }
.export-btn { background: #28a745; color: white; padding: 15px 30px;
border: none; border-radius: 8px; font-size: 16px;
cursor: pointer; text-decoration: none; display: inline-block;
font-weight: bold; transition: all 0.3s; }
.export-btn:hover { background: #218838; transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(40,167,69,0.3); }
.info-box { background: #e7f3ff; padding: 20px; border-radius: 8px;
border-left: 4px solid #0066cc; margin: 20px 0; }
.feature-list { display: grid; grid-template-columns: repeat(2, 1fr);
gap: 10px; margin-top: 15px; }
.feature-item { padding: 10px; background: white; border-radius: 5px;
border-left: 3px solid #28a745; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<cfoutput>
<h1>📊 Sales Performance Dashboard</h1>
<p>Quarter: #currentQuarter# #currentYear# | Report Date: #dateFormat(now(), "mmmm d, yyyy")#</p>
</cfoutput>
</div>
<div class="content">
<cfset totalUnits = 0>
<cfset totalRevenue = 0>
<cfset totalTarget = 0>
<cfloop array="#reportData#" index="row">
<cfset totalUnits += row.units>
<cfset totalRevenue += row.revenue>
<cfset totalTarget += row.target>
</cfloop>
<div class="stats-grid">
<div class="stat-card">
<div class="stat-label">Total Units Sold</div>
<div class="stat-value">
<cfoutput>#numberFormat(totalUnits, "999,999")#</cfoutput>
</div>
</div>
<div class="stat-card">
<div class="stat-label">Total Revenue</div>
<div class="stat-value">
<cfoutput>#dollarFormat(totalRevenue)#</cfoutput>
</div>
</div>
<div class="stat-card">
<div class="stat-label">Total Target</div>
<div class="stat-value">
<cfoutput>#dollarFormat(totalTarget)#</cfoutput>
</div>
</div>
<div class="stat-card">
<div class="stat-label">Achievement</div>
<div class="stat-value" style="color: <cfoutput>#totalRevenue GTE totalTarget ? '##28a745' : '##dc3545'#</cfoutput>">
<cfoutput>#numberFormat((totalRevenue/totalTarget)*100, "999.9")#%</cfoutput>
</div>
</div>
</div>
<div style="text-align: center; margin: 30px 0;">
<a href="?action=export" class="export-btn">
📥 Export to Excel
</a>
</div>
<div class="info-box">
<h3 style="color: #0066cc; margin-bottom: 15px;">✨ Excel Export Features</h3>
<div class="feature-list">
<div class="feature-item">✓ Automatic Excel formulas for calculations</div>
<div class="feature-item">✓ Formatted tables with headers and styling</div>
<div class="feature-item">✓ SUM, SUMIF, and IF functions included</div>
<div class="feature-item">✓ Regional summary with conditional logic</div>
<div class="feature-item">✓ Percentage calculations vs targets</div>
<div class="feature-item">✓ Date-stamped filename for easy filing</div>
</div>
</div>
<h2 style="color: #1e3c72; margin: 30px 0 20px 0;">Sales Data Preview</h2>
<table>
<thead>
<tr>
<th>Month</th>
<th>Region</th>
<th class="number">Units</th>
<th class="currency">Revenue</th>
<th class="currency">Target</th>
<th class="number">vs Target</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<cfloop array="#reportData#" index="row">
<cfset vsTarget = (row.revenue / row.target) * 100>
<tr>
<cfoutput>
<td>#row.month#</td>
<td>#row.region#</td>
<td class="number">#numberFormat(row.units, "999,999")#</td>
<td class="currency">#dollarFormat(row.revenue)#</td>
<td class="currency">#dollarFormat(row.target)#</td>
<td class="number">#numberFormat(vsTarget, "999.9")#%</td>
<td class="#row.revenue GTE row.target ? 'status-met' : 'status-missed'#">
#row.revenue GTE row.target ? '✓ Met' : '✗ Missed'#
</td>
</cfoutput>
</tr>
</cfloop>
</tbody>
</table>
</div>
</div>
</body>
</html>
Browser-based document preview
Legal firms, educational institutions, and corporate training departments require the ability to display documents directly in the browser for immediate viewing without forcing downloads. Users should be able to preview contracts, training materials, policy documents, and certificates in-line while still having the option to download when needed, improving workflow efficiency and reducing storage on client devices.
Problem statement
- Forcing downloads for every document view clutters user download folders unnecessarily
- Users cannot quickly preview documents before deciding to save them locally
- Browser back button doesn't work properly after forced downloads disrupt the navigation flow
- Training materials and policies should be viewable without requiring local file storage
- PDF contracts need to be displayed for review before electronic signature collection
Solution
The cfcontent tag sets the Content-Disposition header to "inline" instead of "attachment" to display documents directly in the browser window. The solution enables immediate document preview for PDFs and other viewable formats, and provides separate view and download actions based on user intent.
<cfset documentVault = {
"POLICY001" = {
title = "Employee Handbook 2024",
type = "application/pdf",
category = "Policy",
icon = "📘",
size = "2.4 MB",
lastUpdated = "2024-01-15"
},
"TRAIN002" = {
title = "Safety Training Manual",
type = "application/pdf",
category = "Training",
icon = "🛡️",
size = "1.8 MB",
lastUpdated = "2024-02-20"
},
"CONTRACT003" = {
title = "Service Level Agreement",
type = "application/pdf",
category = "Legal",
icon = "⚖️",
size = "456 KB",
lastUpdated = "2024-03-10"
},
"CERT004" = {
title = "Compliance Certificate",
type = "application/pdf",
category = "Certificate",
icon = "🏆",
size = "234 KB",
lastUpdated = "2024-01-30"
}
}>
<cfset viewMode = structKeyExists(url, "mode") ? url.mode : "inline">
<cfset accessLog = []>
<!--- Handle document view/download request --->
<cfif structKeyExists(url, "docId") AND structKeyExists(url, "action")>
<cftry>
<!--- Validate document exists --->
<cfif NOT structKeyExists(documentVault, url.docId)>
<cfheader statuscode="404">
<cfoutput>
<h1>404 - Document Not Found</h1>
<p>The requested document does not exist in the vault.</p>
</cfoutput>
<cfabort>
</cfif>
<cfset doc = documentVault[url.docId]>
<!--- Determine content disposition based on action --->
<cfif url.action EQ "view">
<cfset disposition = "inline">
<cfset actionText = "Viewing">
<cfelse>
<cfset disposition = "attachment">
<cfset actionText = "Downloaded">
</cfif>
<!--- Log access --->
<cfset arrayAppend(accessLog, {
timestamp = now(),
docId = url.docId,
docTitle = doc.title,
action = actionText,
disposition = disposition
})>
<!--- For CFFiddle: Simulate document delivery --->
<cfheader name="Content-Disposition" value="#disposition#; filename=#replace(doc.title, ' ', '_', 'ALL')#.pdf">
<cfcontent type="text/plain" reset="yes">
<cfoutput>
#disposition EQ "inline" ? "VIEWING IN BROWSER" : "DOWNLOADING FILE"#
========================================
Document: #doc.title#
Type: #doc.type#
Category: #doc.category#
Size: #doc.size#
Last Updated: #dateFormat(doc.lastUpdated, "mmmm d, yyyy")#
Content-Disposition: #disposition#
#disposition EQ "inline" ? "This document is displayed directly in your browser.
You can read it without downloading. Use browser's built-in
PDF viewer controls. Click 'Download' if you want to save it." : "This document is being downloaded to your computer.
Check your Downloads folder. The file will be saved locally
for offline access and archival."#
Access Details:
- Document ID: #url.docId#
- Access Time: #dateTimeFormat(now(), "yyyy-mm-dd HH:nn:ss")#
- Action: #actionText#
---
PRODUCTION IMPLEMENTATION:
In a production environment, this would use:
<cfheader name="Content-Disposition" value="#disposition#; filename=#doc.title#.pdf">
<cfcontent type="#doc.type#" file="c:\document_vault\#url.docId#.pdf">
The inline mode displays PDFs directly in browser.
The attachment mode triggers download dialog.
</cfoutput>
<cfabort>
<cfcatch type="any">
<cfheader statuscode="500">
<cfoutput>
<h1>Error Loading Document</h1>
<p>An error occurred: #cfcatch.message#</p>
</cfoutput>
<cfabort>
</cfcatch>
</cftry>
</cfif>
<!DOCTYPE html>
<html>
<head>
<title>Document Viewer System</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Arial', sans-serif; background: #ecf0f1; padding: 20px; }
.container { max-width: 1200px; margin: 0 auto; }
.page-header { background: linear-gradient(135deg, #2c3e50 0%, #3498db 100%);
color: white; padding: 40px; border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2); margin-bottom: 30px; }
.page-header h1 { font-size: 36px; margin-bottom: 10px; }
.doc-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px; margin-bottom: 30px; }
.doc-card { background: white; border-radius: 12px; padding: 25px;
box-shadow: 0 5px 20px rgba(0,0,0,0.1); transition: all 0.3s; }
.doc-card:hover { transform: translateY(-5px);
box-shadow: 0 10px 30px rgba(0,0,0,0.15); }
.doc-header { display: flex; align-items: center; margin-bottom: 15px; }
.doc-icon { font-size: 48px; margin-right: 15px; }
.doc-title { font-size: 18px; font-weight: bold; color: #2c3e50; }
.doc-meta { display: grid; gap: 8px; margin: 15px 0; font-size: 14px; color: #7f8c8d; }
.doc-meta-item { display: flex; justify-content: space-between;
padding: 8px 0; border-bottom: 1px solid #ecf0f1; }
.action-buttons { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 15px; }
.btn { padding: 12px; border: none; border-radius: 8px; cursor: pointer;
font-weight: bold; text-decoration: none; display: inline-block;
text-align: center; transition: all 0.3s; }
.btn-view { background: #3498db; color: white; }
.btn-view:hover { background: #2980b9; }
.btn-download { background: #27ae60; color: white; }
.btn-download:hover { background: #229954; }
.info-panel { background: white; padding: 30px; border-radius: 12px;
box-shadow: 0 5px 20px rgba(0,0,0,0.1); margin-bottom: 20px; }
.info-panel h3 { color: #2c3e50; margin-bottom: 20px; }
.comparison { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; }
.comparison-item { padding: 20px; background: #f8f9fa; border-radius: 8px; }
.comparison-item h4 { color: #3498db; margin-bottom: 15px; }
.comparison-item ul { margin-left: 20px; color: #2c3e50; line-height: 1.8; }
.category-badge { display: inline-block; padding: 5px 12px; border-radius: 15px;
font-size: 11px; font-weight: bold; margin-top: 10px; }
.badge-policy { background: #e74c3c; color: white; }
.badge-training { background: #f39c12; color: white; }
.badge-legal { background: #9b59b6; color: white; }
.badge-certificate { background: #16a085; color: white; }
</style>
</head>
<body>
<div class="container">
<div class="page-header">
<h1>📄 Document Viewer & Download Center</h1>
<p>View documents inline or download for offline access</p>
</div>
<div class="info-panel">
<h3>🎯 Inline View vs Download</h3>
<div class="comparison">
<div class="comparison-item">
<h4>👁️ Inline View (Browser Display)</h4>
<ul>
<li>Opens directly in browser window</li>
<li>No download clutter</li>
<li>Quick preview and reading</li>
<li>Browser back button works</li>
<li>Perfect for mobile users</li>
<li>Saves device storage</li>
</ul>
</div>
<div class="comparison-item">
<h4>⬇️ Download (Save Locally)</h4>
<ul>
<li>Saves to Downloads folder</li>
<li>Available offline</li>
<li>Can be archived/shared</li>
<li>Opens in default PDF app</li>
<li>Permanent local copy</li>
<li>Editable annotations</li>
</ul>
</div>
</div>
</div>
<h2 style="color: #2c3e50; margin-bottom: 20px;">📚 Document Library</h2>
<div class="doc-grid">
<cfloop collection="#documentVault#" item="docId">
<cfset doc = documentVault[docId]>
<div class="doc-card">
<div class="doc-header">
<div class="doc-icon">
<cfoutput>#doc.icon#</cfoutput>
</div>
<div>
<div class="doc-title">
<cfoutput>#doc.title#</cfoutput>
</div>
<cfoutput>
<cfswitch expression="#doc.category#">
<cfcase value="Policy">
<span class="category-badge badge-policy">#doc.category#</span>
</cfcase>
<cfcase value="Training">
<span class="category-badge badge-training">#doc.category#</span>
</cfcase>
<cfcase value="Legal">
<span class="category-badge badge-legal">#doc.category#</span>
</cfcase>
<cfcase value="Certificate">
<span class="category-badge badge-certificate">#doc.category#</span>
</cfcase>
</cfswitch>
</cfoutput>
</div>
</div>
<div class="doc-meta">
<div class="doc-meta-item">
<span><strong>Document ID:</strong></span>
<cfoutput><span>#docId#</span></cfoutput>
</div>
<div class="doc-meta-item">
<span><strong>File Size:</strong></span>
<cfoutput><span>#doc.size#</span></cfoutput>
</div>
<div class="doc-meta-item">
<span><strong>Last Updated:</strong></span>
<cfoutput><span>#dateFormat(doc.lastUpdated, "mm/dd/yyyy")#</span></cfoutput>
</div>
<div class="doc-meta-item">
<span><strong>Type:</strong></span>
<span>PDF Document</span>
</div>
</div>
<div class="action-buttons">
<cfoutput>
<a href="?docId=#docId#&action=view" class="btn btn-view">
👁️ View Inline
</a>
<a href="?docId=#docId#&action=download" class="btn btn-download">
⬇️ Download
</a>
</cfoutput>
</div>
</div>
</cfloop>
</div>
<cfif arrayLen(accessLog) GT 0>
<div class="info-panel">
<h3>📊 Access Log</h3>
<cfloop array="#accessLog#" index="entry">
<div style="padding: 10px; background: ##f8f9fa; border-radius: 5px; margin-bottom: 10px;">
<cfoutput>
<strong>#dateTimeFormat(entry.timestamp, "HH:nn:ss")#</strong> -
#entry.docTitle# (#entry.docId#) -
<strong style="color: ##3498db;">#entry.action#</strong> -
Disposition: <code>#entry.disposition#</code>
</cfoutput>
</div>
</cfloop>
</div>
</cfif>
</div>
</body>
</html>