Navigating the Filesystem with Catalyst

In trying to improve the the abality for the user to mangae and organize uploaded files I developed a pretty simple way to navigate the file system for MyApp/root/static using Catalyst::Model::File.


So I started off by adding to MyApp::Model::File


 

package MyApp::Model::File;

use base Catalyst::Model::File;

__PACKAGE__->config(
        root_dir => '/home/fartknocker/MyApp/root/static',
);

1;


 

Then in a controller MyApp::File all I did was


 

sub list : Local {
    my ( $self, $c ) = @_;
    
    # Get the path for the desired directory based on the URI
    my $path = $c->req->path;
        # A little RegEX to get rid of the crap so we have a clean path to the
        # desired directory
        $path =~ s/file\/list//g;
    
    # Stash the path so we can use it for links in the template    
    $c->stash->{path} = $path;
    
    # Actually get the files from the model
    my $dir = $c->model('MyApp::Model::File');
        # Take the cleaned up path from above to change the directory
        my $files = $dir->cd($path);
        # Make a list of the sub directories that exist in the desired directory
        my $dir_names : Stashed = [$files->list( mode => 'dirs', recurse => 0 )];
        # Make a list of the files that exist in the desired directory
        my $file_names : Stashed = [$files->list( mode => 'files', recurse => 0 )];
        # Get the current working directory
        my $pwd = $files->pwd;
        # Stash the parent for a link back up
        my $parent : Stashed = $pwd->parent;
}

 



And then the template:


 

<a href="[% Catalyst.uri_for('/file/list') _ parent %]">[% parent %]</a>
<h3>Directories:</h3>
[% FOREACH dir IN dir_names %]
        [%- "<ul>\n" IF loop.first %]
        <li>
                <a href="[% Catalyst.uri_for('/file/list') _ path %]/[% dir %]">[% dir %]</a>
        </li>
        [%- "</ul>\n" IF loop.last %]
[% END %]

<h3>Files</h3>
[% FOREACH file IN file_names %]
        [%- "<ul>\n" IF loop.first %]
        [% file %]
        [%- "</ul>\n" IF loop.last %]
[% END %]


 

And there it is. Enjoy

UPDATE: I've taken this and made it a more fully functional file management tool. You can read more about it in the wiki.


Posted by jay On: Friday May, 2008 20:31

Comments

Post Comment

Name
Email
Comment
 
Validation Key Image
Key