Create a Zip file and make available for download using Coldfusion 8

Coldfusion 8 has the tag CFZIP by which we can zip/unzip a folder in the server. For creating a file download, that is, the user will be prompted for saving the file, we can use CFHEADER tag. We can use CFCONTENT tag to deliver the content in an unpublished directory (not mapped to web server) to the user.

Now, let us begin with cfzip.

<cfzip action="zip" source="C:\myfiles\myphotos" file="c:\download\myphotos.zip">



The "action" attribute tell the server to 'zip' the contents of the folder specified in "source" attribute and output the zip file as specified in the "file" attribute. So, the files in "C:\myfiles\myphotos" folder will be zipped and saved as "c:\download\myphotos.zip".

We can additionally specify the CFZIPPARAM inside the CFZIP tag to filter only the files matching the filter for the process.

Now we have the zip file in the server in an unpublished directory. We need to make this file available for download.
The tag we use here is CFCONTENT. This tag serves the file in the server storage area to the browser.

<cfcontent file="c:\download\myphotos.zip" deletefile="true" />

This code specify that the file specified in the "file" attribute should be served to the browser and the "deletefile" attribute specify whether to delete the file after this operation.

In some cases like serving text files, some browsers tend to render the content to the page itself instead of downloading or some may not know the action to perform on the file. To guide the browser to show a download prompt, we can use the CFHEADER tag. This tag will create appropriate header for the data served to user's browser.

<cfheader name="Content-Disposition" value="attachment; filename=myphotos.zip">

Put this code above the CFCONTENT code.
This code tell the browser to accept the content as downloadable and show the download prompt.

Note: The folders specified as source and destination should be valid or else the Coldfusion server will show an error.

Comments

Anonymous said…
Thanks. Helped a bunch!
Unknown said…
Thank you so much! The "Put this code above the CFCONTENT code" fixed something that had been a problem for years!
Glad to know that the post helped you.

Popular posts from this blog

Array functions in JavaScript

Hide notification content in Android lock screen for Messages, email, whatsapp and selected apps.