ColdFusion 9 - CFZIP Example

ColdFusion Add comments

I was recently asked to provide a quick link for allowing administrators to download _all_ user uploaded assets for a particular form. The obvious choice for this was to use <CFZIP /> to create an archive, compress the download file size and also provide one download link.

It didn't take very long to do, but I thought I'd share a quick example of this for others who might need the same.

See the code below:

<!--- START BUILDING THE DOCUMENT FILE NAME AND DIRECTORY PATH     --->
<cfset VARIABLES.directoryPath = "\\network\or\drive\path\to\files" />
<cfset VARIABLES.archiveFileName = "myArchive.zip" />

<!--- SET THE CONTENT TYPE TO ZIP ARCHIVE --->
<cfcontent type="application/zip" reset="false" />
<cfheader name="Content-Disposition" value="attachment;filename=#archiveFilename#">

<cftry>
    <!--- CHECK ARCHIVE EXISTS --->
    <cffile action="read"
        file="#VARIABLES.directoryPath#\#VARIABLES.archiveFileName#"
        variable="archiveContent" />

    <!--- IF NOT CREATE IT THEN RE-READ THE CONTENTS --->
    <cfcatch type="any">        
        <cfzip  action="zip"
            source="#VARIABLES.directoryPath#\"
            file="#VARIABLES.directoryPath#\#VARIABLES.archiveFileName#"
            overwrite="yes"
            recurse="no"
            storePath="no"
        />
        <cffile action="read"
            file="#VARIABLES.directoryPath#\#VARIABLES.archiveFileName#"
            variable="archiveContent" />
    </cfcatch>
</cftry>
<!--- OUTPUT THE RESULTS TO THE USER --->
<cfoutput>#archiveContent#</cfoutput>


This is a dumbed down version of the template code, combined to provide an easy example for this post, but in the production version
I actually dynamically build the folder path and filename.  Also, the zip functionality is handled in its own context \  
method, where it should be in the application.

Also, the above code sample is an all-in-one solution for archiving and downloading.  Obviously you would provide the users with a link to this page
with a target attribute with a value of "_blank" so it opens in a new window.

Other than that - happy zipping and downloading.

 

Bookmark and Share

0 responses to “ColdFusion 9 - CFZIP Example”

Leave a Reply

Leave this field empty:

Powered by Mango Blog. Design and Icons by N.Design Studio