ExtJS: Simple File Browser

June 1st, 2011 by aditia rahman / 18 Comments  

     

ExtJS has a lot of great components to build complete web application that can be look like desktop application, In today post I want to show how to create a very simple file browser in ExtJS, with PHP backend we can easily get file and folder on the system.

ExtJS File Browser

First this example have some limitation, I try it on my XAMPP localhost, so I assumed the it is the top parent of all directories, the tree directory only load once when the page is loaded, file preview only in grid component.

download

ExtJS

The example container is based on window component, which have two items inside, they are treePanel and gridPanel, the gridPanel will load dynamically, trigerred when user click on of the tree node.

Ext.onReady(function() {
    store_dir = Ext.create('Ext.data.TreeStore', {
        proxy: {
            type: 'ajax',
            url: 'get_dir.php'
        }
    });

    tree_dir = Ext.create('Ext.tree.Panel', {
        title: 'Localhost Directory',
        rootVisible: false,
        store: store_dir,
        split: true,
        region: 'west',
        collapsible: true,
        floatable: false,
        width: 200,
        useArrows: true,
        listeners: {
            itemclick: {
                fn: function(view, record, item, index, event) {
                    store_file.load({
                        url: 'get_file.php?dir=' + record.data.id
                    });

                    nodeId = record.data.id;
                    htmlId = item.id;
                }
            }

        }
    });

    Ext.define('File', {
       extend: 'Ext.data.Model',
       fields: ['filename', 'filesize', 'filedate']
    });

    store_file = Ext.create('Ext.data.Store', {
        model: 'File',
        proxy: {
          type: 'ajax',
          url: 'get_file.php',
          reader: {
              type: 'json',
              root: 'files'
          }
        }
    });

    grid_file = Ext.create('Ext.grid.Panel', {
        title: 'File List',
        region: 'center',
        store: store_file,
        columns: [
            { header: 'Name', width: 170, dataIndex: 'filename' },
            { header: 'Size', width: 100, dataIndex: 'filesize' },
            { header: 'Last Modified', width: 200, dataIndex: 'filedate' }
        ],
        viewConfig: {
            stripeRows: true
        }
    });

    win = Ext.create('widget.window', {
        title: 'ExtJS Simple File Browser',
        width: 700,
        height: 400,
        layout: 'border',
        bodyStyle: 'padding: 5px;',
        items: [tree_dir, grid_file]
    });

    win.show();
});
PHP (get_dir.php)

This file is for fetching all directory on your XAMPP htdocs directory, using $_SERVER['DOCUMENT_ROOT'] variable. If you have many directory on htdocs, it will take time to load. In this php file I used a recursive function to get all the directory with all the sub directory by one call function, that’s why it will take time to load, and create a json format from it.

<?php

class MyDirectory {

    public $json = '[';

    public function get_children($dir, $child) {
        $dh = opendir($dir);
        while (($file = readdir($dh)) !== false) {
            if ($file != '.' AND $file != '..' ) {
                if (filetype($dir . $file) == 'dir') {
                    // must be checked if this folder have other subfolder
                    if ($this->count_sub_dir($dir . $file . '/') == 0) {
                        $this->json .= '{text:"'.$file.'", leaf: true, id: "'.$dir . $file.'"},';
                    } else {
                        $this->json .= '{text:"'.$file.'", id: "'.$dir . $file.'", children: [';
                        $this->get_children($dir . $file . '/', true);
                    }
                }
            }
        }
        if ($child) {
            $this->json .=  ']},';
        }
        closedir($dh);
    }

    public function count_sub_dir($dir) {
        $dh = opendir($dir);
        $countdir = 0;
        while (($file = readdir($dh)) !== false) {
            if ($file != '.' AND $file != '..' ) {
                if (filetype($dir . $file) == 'dir') {
                    $countdir++;
                }
            }
        }
        closedir($dh);
        return $countdir;
    }
}

$host_dir = $_SERVER['DOCUMENT_ROOT']."/";

$dir = new MyDirectory();

$dir->get_children($host_dir, false);

$dir->json .= ']';
$dir->json = str_replace(",]", "]", $dir->json);

echo($dir->json);

?>
PHP (get_file.php)

And this is the last file to get all the file (without any directory) in specific directory, the parameter sent from ExtJS tree node, when it clicked.

<?php

$dir = $_GET['dir'] . "/";

$dh = opendir($dir);
$files = array();
while (($file = readdir($dh)) !== false) {
    if ($file != '.' AND $file != '..' ) {
        if (filetype($dir . $file) == 'file') {
            $files[] = array(
                'filename' => $file,
                'filesize' => filesize($dir . $file). ' bytes',
                'filedate' => date("F d Y H:i:s", filemtime($dir . $file))
            );
        }
    }
}
closedir($dh);

echo(json_encode(array('files' => $files)));

?>

Well that all hope can give some idea to create much larger application or adding some more feature like icons view (using DataView component), create, edit, delete file, etc.

download
ExtJS File Browser

        submit to reddit Delicious

18 Comments Leave a Comment Subscribe RSS

  • panega says:

    i like this…. superdit menolong saya untuk belajar…. saya senang belajar dari contoh…. trims…. izin unduh mas…

  • narku says:

    Kenapa pas di skrip get_dir.php nggak pakai json_encode tapi di get_file.php pake json_encode
    translate:
    why used json_encode in get_file.php, but not in get_file.php?

    • get_dir aga sulit kalo di convert pake json_encode, karena looping hingga ke semua sub folder, get_file lebih simple hanya satu folder saja yg dibaca, mudah dibuat array nya
      translate
      in get_dir.php it is harder to covert using json_encode, cause it have to loop to all subfolder, while get_file.php only one folder to read it easier to convert to array

  • Satish says:

    Its simply getting blank page even I have folder in htdocs

  • wisnoe says:

    om, extJS CRUD nya gak bisa dipake di versi 4
    mohon panduannya utk bisa running di extJS 4

    thanks

  • lola says:

    please translate the comments. I’ve tried the demo but it doesn’t work. Is it compatible with minor versions of the ext library? Thx.

    Lola

    • I created using ext 4 version, it won’t work on ext 3, since i’m using model, for the first time it will take some time to load all the folder.
      okay I tried to translate the comment

      • lola says:

        Thank you for replying and sorry for the complains about the comments. I’ve seen a comment (I supose) “talking” about Extjs versions and I couldn’t understand. That’s the reason of my “angry” post, sorry again.
        I’m trying to do something like your file explorer but I use version 3.3.3. Can you point me to something compatible. Thank you.

        Lola

  • Taivas says:

    heres a cleaner function for php.

    function dir_walk($dir) {
    $return = array();
    if ($dh = opendir($dir)) {
    while (($file = readdir($dh)) !== false) {
    $obj = (object)array();
    if ($file === ‘.’ || $file === ‘..’) {
    continue;
    }
    if (is_file($dir .”/”. $file)) {
    $obj->leaf = true;

    /* Example how to detect file extension and add icon class
    $ext = end(explode(“.”, $file));
    if ($ext == “js”) {
    $obj->iconCls = “js-file”;
    }
    */
    }elseif(is_dir($dir .”/”. $file)) {
    $obj->children = /*$this->*/dir_walk($dir .”/”. $file);
    }
    $obj->id = $dir .”/”. $file;
    $obj->text = $file;
    $return[] = $obj;
    }
    closedir($dh);
    }
    return $return;
    }

  • Taivas says:

    You can use the above function simply by calling

    echo json_encode(dir_walk(‘.’));

  • keren mas tutorialnya.. thanks :-)

  • armance says:

    great! im glad i found this blog, bookmarked it,thank you

    im trying to do something similar but with a form instead of a grid, basically the form should display the data of the node selected in the tree in order to modify it.
    any suggestions to point me in the right direction..

  • Prakshep says:

    Hi all,

    This is nice but how to add as iteam of treepanel in ext.panel.
    this propotype ext.create not run in my exiting application.

    can you provide without ext.create entire code.
    it is very useful if you guys will give me.

    Thanks

  • Mickel says:

    Hi, it’s not more usefull to use an array and after json_encode for get_dir.php?

    I mean, I think it’s more simple and more flexible to use an array before and transform the array in json.

  • Mike says:

    Not knowing this existed, I created a separate example… with a downloadable sample code archive.. View the article here. This example walks you through the process of creating your own treeview application to view pdf, ppt or doc documents.

    Enjoy,
    Mike

  • ozan says:

    Your tutorial is very useful for me but I have a problem. My problem here after I try the tutorial on the application runs fine. but how do I delete a file or folder. I beg for help.

  • sahil says:

    superb code man, i liked it

Leave a Comment