Force file download

February 27, 2008

To force a file to download instead of opening in the browser use this code:

<cfset variables.filepath = ExpandPath('myfolder') & variables.myfile />

<cfswitch expression="#LCase(ListLast(variables.myfile, "."))#">
  <cfcase value="avi">
    <cfset variables.contentType = "video/x-msvideo" />
  </cfcase>
  <cfcase value="doc">
    <cfset variables.contentType = "application/msword" />
  </cfcase>
  <cfcase value="exe">
    <cfset variables.contentType = "application/octet-stream" />
  </cfcase>
  <cfcase value="gif">
    <cfset variables.contentType = "image/gif" />
  </cfcase>
  <cfcase value="jpg,jpeg">
    <cfset variables.contentType = "image/jpg" />
  </cfcase>
  <cfcase value="mp3">
    <cfset variables.contentType = "audio/mpeg" />
  </cfcase>
  <cfcase value="mov">
    <cfset variables.contentType = "video/quicktime" />
  </cfcase>
  <cfcase value="mpe,mpg,mpeg">
    <cfset variables.contentType = "video/mpeg" />
  </cfcase>
  <cfcase value="pdf">
    <cfset variables.contentType = "application/pdf" />
  </cfcase>
  <cfcase value="png">
    <cfset variables.contentType = "image/png" />
  </cfcase>
  <cfcase value="ppt">
    <cfset variables.contentType = "application/vnd.ms-powerpoint" />
  </cfcase>
  <cfcase value="wav">
    <cfset variables.contentType = "audio/x-wav" />
  </cfcase>
  <cfcase value="xls">
    <cfset variables.contentType = "application/vnd.ms-excel" />
  </cfcase>
  <cfcase value="zip">
    <cfset variables.contentType = "application/zip" />
  </cfcase>
  <cfdefaultcase>
    <cfset variables.contentType = "application/unknown" />
  </cfdefaultcase>
</cfswitch>

<cfheader name="Content-disposition" value="attachment;filename=#variables.myfile#" />
<cfcontent type="#variables.contentType#" file="#variables.filepath#" />

No comments

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.