Greg's Blog

helping me remember what I figure out

Forcing a Download

| Comments

Most browser these are cleaver enough to determine the mime type of documents being served up by the web server and then fire up the application within the browser window. Every now and then though, this is not the desired effect. And doubly so when you want to a little processing before serving up the required document (like say a download counter). This scenario was causing the served up document to occasionally not render properly (read display complete and utter gobbledegook). Displayed below is a small code snippet that will show you how you can force the browser to prompt the user for download, in this case a PDF document.

<cfset local.file = “the full path to your file goes here” />
<cfheader name=”Content-Disposition” value=”attachment; filename=#GetFileFromPath(local.file)#”>
<cfcontent type=”application/pdf” file=”#local.file#” />

The first and third line would normally be used to serve a file of a different content type. This time round it’s a PDF document. The trick to forcing the browser to prompt the user for action lies in the <cfheader> tag, namely by specifying an attribute value and giving it a value of attachment, separated by a semi colon (;) and followed by the full path and file name again. Et Voila, load the page and dialogue pops up. Omit it and the <cfheader> tag and the PDF file will display in-line.