The cfcontent
tag downloads files from the server to the client. You can use this tag to set the MIME type of the content returned by a ColdFusion page and, optionally, define the filename of a file to be downloaded by the current page. By default, ColdFusion returns a MIME content type of text/html so that a web browser renders your template text as a web page.
As with cffile
and cfdirectory,
you can disable cfcontent
processing in the ColdFusion Administrator.
A MIME type is a label that identifies the contents of a file. the browser uses the MIME type specification to determine how to interact with the file. For example, the browser could open a spreadsheet program when it encounters a file identified by its MIME content type as a spreadsheet file.
A MIME content type consists of "type/subtype"
format. The following are common MIME content types:
You use the cfcontent
tag to change the MIME content type that returns to the browser along with the content generated from your ColdFusion page.
The cfcontent
tag has one required attribute, type
, which defines the MIME content type returned by the current page.
<h1>cfcontent_message.htm</h1> <p>This is a <em>test message</em> written in HTML.</p> <p>This is the <em>second paragraph</em> of the test message. As you might expect, it is also written in HTML.</p>
This HTML file will be called by the ColdFusion file that you write in steps 3 through 7.
<html> <head> <title>cfcontent Example</title> </head> <body> <h3>cfcontent Example</h3> <cfcontent type = "text/html" file = "C:\CFusionMX\wwwroot\myapps\cfcontent_message.htm" deleteFile = "No"> </body> </html>
file =
line to point to your myapps directory.
The text of the called file (cfcontent_message.htm) displays as normal HTML, as shown in the following figure:
type = "text/html"
to type = "text/plain"
.
The text displays as unformatted text, in which HTML tags are treated as text:
The following example shows how the cfcontent tag can create an Excel spreadsheet that contains your data.
<!--- use cfsetting to block output of HTML outside of cfoutput tags ---> <cfsetting enablecfoutputonly="Yes"> <!--- get employee info ---> <cfquery name="GetEmps" datasource="CompanyInfo"> SELECT * FROM Employees </cfquery> <!--- set vars for special chars ---> <cfset TabChar = Chr(9)> <cfset NewLine = Chr(13) & Chr(10)> <!--- set content type to invoke Excel ---> <cfcontent type="application/msexcel"> <!--- suggest default name for XLS file ---> <!--- use "Content-Disposition" in cfheader for Internet Explorer ---> <cfheader name="Content-Disposition" value="filename=Employees.xls"> <!--- output data using cfloop & cfoutput ---> <cfloop query="GetEmps"> <cfoutput>#Employee_ID##TabChar##LastName# #TabChar##FirstName##TabChar##Salary##NewLine#</cfoutput> </cfloop>
The data appears in an Excel spreadsheet: