FileSystem API in HTML5 - Creating/Removing folders in browser

Sheonarayan
Posted by in HTML 5 category on for Advance level | Points: 250 | Views : 11932 red flag
Rating: 5 out of 5  
 2 vote(s)

In this article, we are going to learn how to create a folder and remove a folder within the browser using FileSystem API in HTML5.


 Download source code for FileSystem API in HTML5 - Creating/Removing folders in browser

Recommendation
Read FileSystem API in HTML5 - Working with Files in the browser before this article.

Introduction


In the last article, we learnt how to create/edit a File, Rename a file and Remove a file within the browser using FileSystem API in HTML5 supported browser. In this article, we shall learn how to create a directory/sub directory and remove a directory / sub directory within the browser.


Pre-requisite 


Basic knowledge of HTML5 and intermediate knowledge of JavaScript are required to understand this article. We would also recommend to read last article of creating files in the browser so that the basics of going ahead with FileSystem API in HTML5 is understood properly.

User Interface to manage folders in browser


To understand managing folders within browser, we have following user interface created and below is the HTML code for this.
<fieldset>
            <legend>Create Folder</legend>
            <p>
                Folder name:
                <input type="text" placeholder="Write folder name to create" name="folderName" id="folderName" />
            </p>
            <input type="button" value="Create Folder" onclick="CreateFolder()" /> | <a href="files.html">Files</a>
    </fieldset>
        <fieldset>
            <legend>List folder details</legend>
            <p>
                Folder content to list:
                <input type="text" placeholder="Write folder name to create" name="folderNameL" id="folderNameL" />
            </p>
            <input type="button" value="List Folders and Files" onclick="ListFoldersFiles()" /> 
            <input type="button" value="Delete Folder" onclick="DeleteFolders()" /> 
        </fieldset>


    <ul id="folderList"></ul>


The first fieldset provides ability to create a folder and second fieldset provides ability to List the folders / sub folders and remove them.


Setting up the environment to create / remove a folder within the browser


In below code, we have set the window.requestFileSystem value to the appropriate object based on what browser is being used by the end user.

If the requestFileSystem object exists, we are calling InitFileSystem() function that instantiate the PERSISTENT object by specifying the size of space it needs (1024 *1024) in bytes. That in tern sets the fs value to the file system object that is going to be used through out the page.
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
        var fs = null;

        // INITIALIASE
        function InitFileSystem() {
            window.requestFileSystem(window.PERSISTENT, 1024 * 1024, function (filesystem) {
                fs = filesystem;

                ListFoldersFiles();
            }, handleError);
        }

        // Start the application
        if (window.requestFileSystem) {
            InitFileSystem();
        } else {
            alert('Sorry! Your browser doesn\'t support the FileSystem API :(');
        }
Next, it calls the ListFoldersFiles() function that list the folders created under root in the browser.

Listing folders created in the browser using FileSystem API

        //  LIST DIRECTORY
        function ListFoldersFiles() {
            var path = document.querySelector("#folderNameL").value;
            document.querySelector('#folderList').innerHTML = '';
            if (path.length > 0)
            {
                ListFoldersFilesContent(path)
            }
            else
            {
                ListDirectories();
            }             
        }
Based on folder name textbox (from 2nd fieldset) value, it calls ListDirectories() [if no path specified, list root folders] or ListFoldersFilesContent(path) [if path specified, list sub folders or files of that folder] method.

ListDirectories() method

This method creates a reader object and defines a function called ReadEntries that read the entries of the current folder recursively and list in the un ordered list.
 function ListDirectories() {
            var dirReader = fs.root.createReader();
            var entries = [];

            // Call the reader.readEntries() until no more results are returned.
            function ReadEntries() {
                dirReader.readEntries(function (results) {

                    if (!entries.length) {
                        document.querySelector('#folderList').innerHTML = 'No files or folders exists.';
                    } else {
                        document.querySelector('#folderList').innerHTML = '';
                    }

                    if (!results.length) {
                        ListResults(entries.sort());
                    } else {
                        entries = entries.concat(results);
                        ReadEntries();
                    }
                }, handleError);
            };

            ReadEntries(); // Start reading dirs.
        }

ListResults() function

This function loop through each value of the entries and creates an li element with files or folder icons based on whether the current entry is File or Folder. The same element is then appended to the ul element exists on the web page.
        function ListResults(entries) {

            entries.forEach(function (entry, i) {
                var img = entry.isDirectory ? '<img src="/images/folder.jpg" /> ' :
                                                        '<img src="/images/file.jpg" /> ';

                var li = document.createElement('li');
                li.innerHTML = img + ' ' + entry.name;

                document.querySelector('#folderList').appendChild(li);
            });
        }

ListFoldersFilesContent(path) function

This function executes when end user has entered the path name in the 2nd text box and clicked on the "List Folders and Files" button. It gets the Directory based on the path passed and creates a reader. Remaining code is almost same as the above function. 
function ListFoldersFilesContent(path)
        {            
            fs.root.getDirectory(path, {}, function (dirEntry) {
                var dirReader = dirEntry.createReader();
                dirReader.readEntries(function (entries) {

                    entries.forEach(function (entry, i) {
                        var img = entry.isDirectory ? '<img src="/images/folder.jpg" alt="Folder" /> ' :
                                                        '<img src="/images/file.jpg" alt="Files" /> ';

                        var li = document.createElement('li');
                        li.innerHTML = img + ' ' + entry.fullPath;

                        document.querySelector('#folderList').appendChild(li);
                    });
                }, handleError);
            }, handleError);
        }
        

How to Create a folder in the browser?


When the first button [Create Folder] button is clicked, the CreateFolder function executes. This gets the value of the first text box and pass to the CreateDir function (else block). 

function CreateFolder() {
            if (document.querySelector('#folderName').value.length == 0) {
                alert("Please enter folder name to create!");
                return false;
            }
            else
            {
                var path = document.getElementById("folderName").value;
                CreateDir(fs.root, path.split('/')); // fs.root is a DirectoryEntry.
                ListFoldersFiles();
                alert("Folder created !");
            }
        }

CreateDir() function

This function creates the directory recursively (In case the text box value is like folder/subfolder/subfolder), the 2nd parameter of getDirectory function (create: true) instruct the method to create the directory.
//  CREATE DIRECTORY
        function CreateDir(rootDirEntry, folders) {
            // remove the bad folder name like .
            if (folders[0] == '.' || folders[0] == '') {
                folders = folders.slice(1);
            }
            rootDirEntry.getDirectory(folders[0], { create: true }, function (dirEntry) {
                // Recursively add the new subfolders, if any
                if (folders.length) {
                    CreateDir(dirEntry, folders.slice(1));
                }
            }, handleError);
        }

How to remove a folder in the browser?


To remove a folder, we get the folder name to remove (from 2nd text box) and pass the path to the getDirectory, then call the remove method.
function DeleteFolders() {
            var thisPath = document.querySelector('#folderNameL').value;
            // alert(fs);
            fs.root.getDirectory(thisPath, {}, function (dirEntry) {

                dirEntry.remove(function () {
                    alert("Directory removed.");
                    document.querySelector("#folderNameL").value = '';
                    ListFoldersFiles();
                }, handleError);

            }, handleError);
        }

The handleError function is same as explained in the last article that simply shows proper message based on error code returned while working with FileSystem API in the browser.

Conclusion


Hope this and previous article on FileSystem API solves all doubts about working with files and folders in the HTML5 supported browser. For any question or clarification, please feel free to respond to this article.

Thanks for reading, do subscribe for RSS feed to get the new article notification directly in your Inbox.
Recommendation
Read Forms authentication in Lightswitch using MVC Part 4 after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com

Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)