AdobeStock_455007340

ColdFusion Ajax Tutorial 5: File System Browsing With The Tree Control

has been part of ColdFusion since CF2 – originally a Java applet, and then a Flash control, and in ColdFusion 8 an HTML tree control with powerful Ajax support. To demonstrate how to use the new HTML , here is an example that will let you browse the file system tree on your server. What makes this an Ajax control is that the entire tree is not loaded on startup. Rather, it is loaded incrementally, minimal data is loaded on startup, and when a node is expanded an asynchronous call is made back to the server to obtain the children for that node, and so on. This improves performance (by not requiring that entire trees be loaded if they are not needed), and also simplifies actual tree data (formatting and parsing nested tree data is not pretty).
The client-side code for this example is really simple, as seen here:





This uses a “bind” to point to a CFC method to obtain tree contents. When a binding is used, as it is here, only a single may be specified, and it is responsible for loading all data as needed. On initial tree load the CFC method is invoked (passing an empty string for the current path and value), and then as branches are expanded the CFC method is invoked again (passing the current path and value back to the server).
It is worth noting that, by default, results are cached on the client. So expanding and collapsing a branch repeatedly does not trigger multiple CFC method calls. Caching can be disabled if needed.
The CFC method that the is bound to is shown here:



















































expects the bound CFC method to return an array of entries represented as structures. These structures should, at a minimum, contain two members – “display” is the string to be displayed in the tree, and “value” is the value to be returned (back to the bound CFC when branches are expanded, as well as when the form containing the is actually submitted). The structures may also contain additional members (equivalent to the attributes supported by ), for example, “img” and “imgopen”. One important optional member is “leafnode” which tells the tree whether or not the current entry is a leaf (has no children) or a branch (could have children). As tree data is loaded as needed, can’t know if a branch has children until the user tries to expand it. In this example we want folders to be expandable, but not files, and so is set to “true” for file entries.
If the method is being invoked for the top level of the tree (in which case ARGUMENTS.value will be an empty string) then a function is called to get all system drives (or roots). The code then loops through the results, creating a structure for each, and appending these to a results array. If the method is being invoked for a child branch (in which case ARGUMENTS.value will contain the path to the branch that was expanded), is used to obtain the contents of that folder, and then the results are looped over, creating a structure for each entry, and again appending these to a results array.
This example returns all file and folders. If you wanted to return a subset of data, perhaps to allow the user to find files of a specific type, you’d just need to modify the , possibly replacing it with two calls, one for folders and one for the files (using a filter to select just the files you want).
This method refers to a function named getDrives() (to obtain drives or roots) and a variable named THIS.separator (used to refer to the OS specific path separator character), both of which need to be defined. The following is the complete dirtree.cfc, containing the previously seen getDirEntries() method, as well as all supporting code:



















































































As you can see, once you get your arms around how data is formatted and passed back and forth, the new Ajax enabled HTML based is both powerful and really easy to use.

35 responses to “ColdFusion Ajax Tutorial 5: File System Browsing With The Tree Control”

  1. Gary Funk Avatar
    Gary Funk

    Thank you Ben.

  2. Jose Avatar
    Jose

    I get a blank screen in FF and a JS error in IE 7 when I try the sample code, http://h127449.cf8beta.com/cftree.cfm

  3. Ben Forta Avatar
    Ben Forta

    Jose, I tested it in FF2 and IE7, and both worked. Can you get any Ajax controls to work? I wonder if the CFIDE mapping is missing or something like that.
    — Ben

  4. Jose Avatar
    Jose

    Actually, it doesn’t look like I can get the simple (no CFC) Auto Suggest example to work either.
    http://h127449.cf8beta.com/autoSuggest2.cfm
    Should I tell the hosting company to create a virtual directory for CFIDE?

  5. Gary Funk Avatar
    Gary Funk

    Ben, in the function getDirEntries, you have ‘path’ as the first argument. I don’t see where path is ever used. What would this be used for?

  6. Dan Avatar
    Dan

    Jose,
    You either have to have them create a virtual directory for the /CFIDE folder or just upload that folder to your home root directory

  7. Ben Forta Avatar
    Ben Forta

    Gary, value returns whatever value you provided previously for the entry, path returns the dynamically constructed path down the tree. As I build the value to be the full path I am just using that for subsequent searches, that’s simpler in this case as <CFDIRECTORY> needs the full path to get listings. But if this were a sequential database lookup for example, then I’d probably want the value to be the primary key, in which case the path would be useful to know the path down the tree to the current branch.
    — Ben

  8. Gary Funk Avatar
    Gary Funk

    Yes, that’s clear. I missed that one. Will this worked with mapped networked drives? So far, I’m not having any luck in that area.

  9. Ben Forta Avatar
    Ben Forta

    Gary, I am not sure about that one. My guess is that if CF itself sees the mapped drive then it should work (and this will likely require that CF run as a user with rights to those remove shares).
    — Ben

  10. Dan G. Switzer, II Avatar
    Dan G. Switzer, II

    I ran across a blog entry by Nathan Mische yesterday, which shows how to hook into the YUI library to add a context menu to CFTREE. This seems like a perfect companion article to this entry, so I thought I’d post the link:
    http://www.mischefamily.com/nathan/index.cfm/2007/6/4/ColdFusion-8–Tapping-Into-the-Power-of-the-YUI
    -Dan

  11. Jose Avatar
    Jose

    Guys,
    Thanks for your help. I got it to work by adding /CFIDE. However, it takes an eternity to return and then if I click on a subfolder Firefox eventually crashes.

  12. Ben Forta Avatar
    Ben Forta

    Jose, I’ve not seen that happen. What version of FF? All I can think of is that the folder list may be so huge on that shared box that the control is having a hard time with it, but that’s a guess.
    — Ben

  13. Jose Avatar
    Jose

    I’m running FF 2.0.0.4, and you’re probably right regarding the lengthy folder list although I can’t tell for sure..

  14. Dan G. Switzer, II Avatar
    Dan G. Switzer, II

    @Ben:
    I’m also seeing the code lock up on my laptop in FF2.0.0.4. I’ll look in to and and report what I find. I think this potentially could be an issue with the CFMX internal web server. I seem to recall I’ve had issues using it w/AJAX in the pas

  15. Raul Riera Avatar
    Raul Riera

    Actually my FF crashed too when looking at Jose’s example, im using the latests version of it as well.

  16. Ben Forta Avatar
    Ben Forta

    It *looks* like this happens when the folder list is massive (thousands of entries), but without seeing that file system I can’t know for sure. C: expands for me fine (using your URL, Jose). Jose, can you do a <cfdirectory action="list"> and see what it returns for the branch you were trying to expand?
    — Ben

  17. Gary Funk Avatar
    Gary Funk

    My Application.cfc seems to be causing some greif to this poor thing. I get the following error:
    error:widget: Bind failed for tree dirtree, bind value is not a 1D array of key value pairs
    info:http: CFC invocation response:
    info:http: HTTP GET /test/dirtree.cfc?method=getDirEntries&returnFormat=json&argumentCollection=%7B%22path%22%3A%22%22%2C%22value%22%3A%22%22%7D&_cf_nodebug=true&_cf_nocache=true
    info:http: Invoking CFC: /test/dirtree.cfc , function: getDirEntries , arguments: {"path":"","value":""}
    info:widget: Created tree, id: dirtree
    info:widget: Created tree, id: dirtree
    info:LogReader: LogReader initialized
    info:global: Logger initialized

  18. Ben Forta Avatar
    Ben Forta

    Gary, try calling the CFC method with a <CFINVOKE>, and see if it is throwing an error or what is being returned.
    — Ben

  19. Gary Funk Avatar
    Gary Funk

    Ben, when I comment out the following from Application.cfc it works as you wrote it. This is from Ray’s Application.cfc
    <cffunction name="onRequest" returnType="void">
    <cfargument name="thePage" type="string" required="true" />
    <cfinclude template = "#arguments.thePage#" />
    </cffunction>

  20. Dan G. Switzer, II Avatar
    Dan G. Switzer, II

    @Ben: My C: drive only has 69 entries in it and that causes the crash.

  21. Ben Forta Avatar
    Ben Forta

    Gary, yep, onRequest and ACCESS="remote" don’t play nicely together.
    — Ben

  22. Dan G. Switzer, II Avatar
    Dan G. Switzer, II

    @Ben:
    I played around with this a bit more and the issue seems to be with either the CFTREE.js or the CFAJAX.js. I can invoke the CFC URL directly with FF and the page loads just fine, so something is happening when the code is being deserialized i

  23. Gary Funk Avatar
    Gary Funk

    As usual, Ray and SEan have the answer, and it’s a simple fix.
    http://ray.camdenfamily.com/index.cfm?mode=entry&entry=ED9D4058-E661-02E9-E70A41706CD89724
    You can use web services, flash remoting or event gateway requests CFC’s with an Application.cfc containing an onRequest method. This can be done by creating another application.cfc within a subfolder where your CFC’s are, containing the code…
    <cfcomponent name="Application" extends="test.Application">
    <cfset StructDelete(variables,"onRequest")/>
    <cfset StructDelete(this,"onRequest")/>
    </cfcomponent>
    This is why I am a CF coder. At any given moment, each of us is a beginner or an expert and we help each other.

  24. Marius M Avatar
    Marius M

    Thanks Ben for all the new examples for CF8.
    There is definitely a problem with FF (2.0.0.4). Looks like a memory leak. I had to kill FF when memory jumped over 400Mb.
    In IE it works better but it takes forever to load the information when expanding a directory.
    I have seen this behavior in other instances where controls are bind and the information retrieved is rather large, the browser just hangs.
    I really hope that the development team will fix this otherwise I see all of this functionality as having a negative effect on CF in general because you can be it will be used in enterprise environments where is not uncommon to deal with thousands of records and if it’s that slow the reaction is that CF is not good as an enterprise solution.

  25. Kurt Avatar
    Kurt

    It looks like there is a lot of extra code for looping through drive letter contents. What would the dirtree.cfc look like if we just wanted to loop through a certain directory?

  26. Chris Avatar
    Chris

    To get a specific Directory I added the following code to replace the CFDIRECTORY tag in the CFC.
    <CFIF #arguments.VALUE# EQ "">
    <cfdirectory action="list" directory="{directoryname}" name="dir" sort="type">
    <CFELSE>
    <cfdirectory action="list" directory="{directoryname}#arguments.value#" name="dir" sort="type">
    </CFIF>
    Also I added a line to put in a href for the files. I put it after the IF statement checking whether it is a file. See below.
    <CFIF #arguments.value# EQ "">
    <cfset entry.href="/documentation/files/#session.support.release#/#name#">
    <cfelse>
    <cfset entry.href="/Documentation/files/#session.support.release#/#arguments.value#/#name#">
    </CFIF>

  27. Steven Avatar
    Steven

    Hi, Ben:
    I have tried this feature. It’s cool. Just wonder if I could add href and browse the file from this cftree. Unfortunately I can’t make it work via entry.href and entry.target, or using dynamically cftreeitem or cftreeitemvalue, etc.
    Thanks,
    Steven

  28. Jason Avatar
    Jason

    To those who are seeing browsers lock up when many nodes are returned: I had this problem until I enabled whitespace management in CF Administrator. <cfprocessingdirective suppresswhitespace="Yes"> did not help however.

  29. Jason Avatar
    Jason

    Just found you don’t have to enable the server wide whitespace management setting if you make sure the cffunction tag in the cfc has the attribute output="No"..

  30. michael Avatar
    michael

    The code is cool. I am trying to figure out how to make it start at a specific directory C:/intepub/test/files/ vs. A:/ C:/ D:/ … I have tried everything I can think of and I just cant get it narrowed down.
    Also I dont know if this is a Vista problem but my old Tree using the applet worked fine until I upgraded my PC to Vista now it returns paths like this..
    C:\InetpubC:\InetpubtestC:\InetpubtestfilesC:\InetpubtestfilesBrettFischerWeb-3DGroinandHipStretching.flv
    Basically relooping for each directory it looks at. That and it adds the \ infront of the C:
    The CFC version in this code is doing the same thing.
    Any help would be greatly appreciated.

  31. Brendan Avatar
    Brendan

    Any idea on how to start the directory broswing from a certain folder on a drive?

  32. Jens Langenbach Avatar
    Jens Langenbach

    hey there ben,
    i’ve tried this tutorial using cf9 and i went over a little, let’s call it feature ;D
    if u’re trying to open a tree-item thats indeed a dvddrive or a floppydrive, the javascript crashed (at least i think its a javascript, haven’t really looked at it yet)
    so just wanted to come back to you with a little bugreport
    hope you’re doing fine, keep up the good work, couple of your tutorials really got me off the slack 🙂

  33. Ed Avatar
    Ed

    I am trying to figure out how to make it start at a specific directory /var/www/html
    Any help would be greatly appreciated.
    Thank’s

  34. Sean McNeill Avatar
    Sean McNeill

    For those not wishing to list the specific drives, but starting the default entry into a sub directory. This worked for me. I copied the existing function getDirEntries and pasted it in the same component and renamed the function to getMediaDrive
    I then added two additional local variables to the function as follows:
    <cfset var defaultPath = "/u01/media/htdocs/htmlemail/" />
    <cfset var defaultValue = "Media Drive" />
    Then in the if condition where arguments.value IS an empty string (<cfif arguments.value IS "">), simply remove or comment out the invocation of getDrive() as well as the query loop. Your code should look something like this.
    <cfset var defaultPath = "/u01/media/htdocs/htmlemail/" />
    <cfset var defaultValue = "Media Drive" />
    <!— Check if top level —>
    <cfif arguments.value IS "">
    <cfset entry=StructNew()>
    <cfset entry.value = defaultPath />
    <cfset entry.display = defaultValue />
    <cfset entry.img="fixed">
    <cfset arrayAppend(result, entry)>
    <cfelse>
    …. The rest of the code
    </cfif>

  35. Alexandre Avatar
    Alexandre

    great! this code work fine. So how can I make the link of each file open (.doc, .pdf, .txt, …) when the user click it ?

Leave a Reply

Discover more from Ben Forta

Subscribe now to keep reading and get access to the full archive.

Continue reading