now musing at www.aliaspooryorik.com!

February 27, 2008

Force file download

Filed under: ColdFusion — aliaspooryorik @ 11:11 am

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 Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.