Skip to content

Instantly share code, notes, and snippets.

@adamcameron
Last active December 16, 2015 21:29
Show Gist options
  • Save adamcameron/5500604 to your computer and use it in GitHub Desktop.
Save adamcameron/5500604 to your computer and use it in GitHub Desktop.
Does a file / directory listing of the specified directory, kind of emulating the directory-browsing functioanlity of a web server.
<cfscript>
// directory to create listing for, defaulting to the current one
param name="URL.dir" type="string" default=getDirectoryFromPath(getCurrentTemplatePath());
dirCurrent = createObject("java", "java.io.File").init(URL.dir).getCanonicalPath();
dirBase = createObject("java", "java.io.File").init(expandPath("/")).getCanonicalPath();
slash = createObject("java", "java.io.File").separatorChar; // As this displays I'm gonna incur Sean's wrath and use the "correct" slash for the sake of UX
// create the domain/port part of the URL
urlBase = "http://" & CGI.http_host;
if (len(CGI.http_port)){
urlBase &= ":" & CGI.http_port;
}
if (findNoCase(dirBase, dirCurrent) && directoryExists(dirCurrent)){ // make sure we're looking at a real location, and within the webroot
// Used for building links to files
relativePath = replaceNoCase(dirCurrent, dirBase, "", "ONE");
urlPath = replaceNoCase(relativePath, "\", "/", "ALL");
// provide a link to go up a level
parentDir = listDeleteAt(dirCurrent, listLen(dirCurrent, "\/"), "\/");
parentLinkUrl = CGI.script_name & "?dir=" & parentDir;
writeOutput('<a href="#parentLinkUrl#">[Parent Directory]</a><br>');
// list the contents of the directory
files = directoryList(dirCurrent, false, "query", "", "name asc");
writeOutput("<ul>");
for (i=1; i <= files.recordCount; i++){
linkText = files.name[i];
if (files.type[i] == "dir"){
// we just want to link back to this file, passing the dir
linkUrl = CGI.script_name & "?dir=" & dirCurrent & slash & files.name[i];
linkText &= "/"; // just to make it more clear it's a dir
}else{
// we want a link to the actual file
linkUrl = urlPath & "/" & files.name[i];
}
writeOutput('<li><a href="#linkUrl#">#linkText#</a></li>');
}
writeOutput("</ul>");
}else{
// 404 them
writeOutput("Not Found");
cfheader(statuscode=404, statustext="Not Found");
}
</cfscript>
<cffunction name="cfheader"><!--- HOW bloody annoying is it to have to do this! --->
<cfheader attributecollection="#arguments#">
</cffunction>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment