Use CFDirectory to Filter Document Types by File Extension

Ben Nadel was sharing some good information he brought back from cf.Objective() where he showed how to use CFDirectory to filter using a single character wild card.

A reader commented that it would be nice to filter based on a limited set of file extensions. I responded simply that it could be done and gave a brief example.

I thought it would be worthy of mention here to show how I've used it in some of my applications.

As would be expected, we would attempt to separate filters by using a comma (,). However, this method does not work with CFDirectory. Awhile ago when I ran into this, I began trying other "OR" switches, and low and behold the pipe (|) did the trick.

I sometimes create a download directory in my web applications which often ends up being filled up with all kinds of documents that have been uploaded either on the front- or back-end. I wanted a way to just read what was in that directory without having to connect via FTP, etc.

I just created a simple index.cfm file that resides in the download directory (or folder). You can name it what you want, or even place it where you want, but would only need to update the directory read path, etc.

Here you go:

>

<cfset request<.tqru erbygStcroinlgo r= =get"P#ag#e#Cointiefxt((c)u.rgertReenqutersto(w). gMetOQDu er2y,S trDiEng(()' E/0>E8
F<0'cf)o,utDpuEt(>#'rFeqFuFeFstF.Fqu'e)ry)St#r"in
g#>

<    /cfoutput>
<td<>cfabort />

<a href="#dir.name#">#dir.name#</a></td>
    <td align="right">#dir.size#</td>
    <!---
        Convert the filesize to either KB or MB for readability
    --->

    <td align="right"><cfif dir.size GT "1000000">#numberformat(dir.size*.000001, 9.99)#Mb
    <cfelse>#numberformat(dir.size*.001, 9)#kb</cfif></td>
    <td>#dateformat(dir.dateLastModified, "mm/dd/yyyy")# #timeformat(dir.dateLastModified, "long")#</td>
</tr>
</cfoutput>
</table>
<cfoutput>
<p>Document ##: #dir.recordcount#</p>
</cfoutput>
</cfif>
</body>
</html>
</cfprocessingdirective>

And that's it! Hope it helps you in your current or next ColdFusion project.

Comments

Updated the code example to filter for both 3- and 4-letter Microsoft extensions (i.e., *.doc*|*.ppt*).

Thank you Matthew Abbott. http://www.bennadel.com/index.cfm?dax=blog:1219.vi...
# Posted By Stephen Withington | 7/25/08 1:45 PM
Yes, it did help! Thanks!
# Posted By Nic | 9/11/08 1:53 PM

© 2025, Stephen J. Withington, Jr.  |  Hosted by Hostek.com

Creative Commons License   |   This work is licensed under a Creative Commons Attribution 3.0 Unported License.