File download using Coldfusion

In some applications, we may require to give file download to users. In order to protect the files from hackers, you may want to hide the actual path of the file and just stream the data to the user. This small script can stream the data to client browser based on the file name. You may be able to customise this for your application. You need to change two parameters to use this script. First one is the filename and second one is the file directory path.



Code:

<cfparam name="url.filenamename" default="">

<cfset url.filename="/paththo/file">

<cfif trim(url.filename) neq "">
 <!--- mime type --->
   <cfset strFileExt=mid(url.filename,find(".",url.filename,len(url.filename)-3)+1,3)>
   <cfswitch expression="#strFileExt#">
    <cfcase value= "asf">
          <cfset lcl_content = "video/x-ms-asf">
    </cfcase>
    <cfcase value= "asp">
          <cfset lcl_content = "text/asp">
    </cfcase>   
    <cfcase value= "avi">
            <cfset lcl_content = "video/avi">
    </cfcase>   
    <cfcase value= "doc">
             <cfset lcl_content = "application/msword">
    </cfcase>   
    <cfcase value= "gif">
          <cfset lcl_content = "image/gif">
    </cfcase>       
    <cfcase value= "htm,html" delimiters=",">
          <cfset lcl_content = "text/html">
    </cfcase>       
    <cfcase value= "jpg,jpeg" delimiters=",">
          <cfset lcl_content = "image/jpeg">
    </cfcase>
    <cfcase value= "txt">
         <cfset lcl_content = "text/plain">
    </cfcase>
    <cfcase value= "wav">
          <cfset lcl_content = "audio/wav">
    </cfcase>
    <cfcase value= "xls">
          <cfset lcl_content = "application/vnd.ms-excel">
    </cfcase>
    <cfcase value= "zip">
          <cfset lcl_content = "application/zip">
    </cfcase>
    <cfcase value= "mp3">
          <cfset lcl_content = "audio/mpeg3">
    </cfcase>
    <cfcase value= "mpg,mpeg" delimiters=",">
            <cfset lcl_content = "video/mpeg">
    </cfcase>
    <cfcase value= "pdf">
         <cfset lcl_content = "application/pdf">
    </cfcase>
    <cfcase value= "rtf">
         <cfset lcl_content = "application/rtf">
    </cfcase>   
    <cfdefaultcase>
    <!--- all the other headers are handled herre --->
         <cfset lcl_content = "application/octet-stream">
   </cfdefaultcase>   
</cfswitch>

<cfheader name="content-disposition" value="attachment;filename=#trim(url.filename)#">
<cfcontent type="#lcl_content#" file="#trim(url.filename)#" deletefile="No">


"attachment" in <cfheader tag will prompt the user with a download box.
"inline"will write file to clients browser with out prompting it.

If you have any comments about this article please post your comments here.

Commentaires

Posts les plus consultés de ce blog

XAJAX with PHP – The future of web development

XAJAX with PHP – The future of web development

Database connection pooling in ADO.Net