Managing Items Hierarchy with JavaScript WebDAV Library

The IT Hit WebDAV Ajax Library provides the following core classes:

WebDAVSession - represents a session for accessing WebDAV server.

Folder - represents a folder on a WebDAV server.

File - represents a file on a WebDAV server.

HierarchyItem - the base class for files and folders.

Below we will describe how to list folder contents, create, copy, move and delete files and folders. All operations described in this article are supported by any Class 1 compliant WebDAV server.

Listing Folder Children

To list folder content use Folder.GetChildrenAsync method.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>IT Hit WebDAV Ajax Library</title>
    <script src="http://www.ajaxbrowser.com/ITHitService/WebDAVAJAXLibrary/ITHitWebDAVClient.js" type="text/javascript"></script>
    <script type="text/javascript">
        var sFolderUrl = 'http://localhost:35829/';
        var oSession = new ITHit.WebDAV.Client.WebDavSession();

        oSession.OpenFolderAsync(sFolderUrl, null, function (oFolderAsyncResult) {
            if (!oFolderAsyncResult.IsSuccess) {
                console.error(oFolderAsyncResult.Error);
                return;
             }

            /** @typedef {ITHit.WebDAV.Client.Folder} oFolder */
            var oFolder = oFolderAsyncResult.Result;

            console.log(oFolder.Href);

            oFolder.GetChildrenAsync(false, null, function (oAsyncResult) {
                if (!oAsyncResult.IsSuccess) {
                    console.error(oFolderAsyncResult.Error);
                    return;
                }

                /** @typedef {ITHit.WebDAV.Client.HierarchyItem[]} aHierarchyItems */
                var aHierarchyItems = oAsyncResult.Result;

                for (var i = 0, l = aHierarchyItems.length; i < l; i++) {
                    var sSize = aHierarchyItems[i].ResourceType !== ITHit.WebDAV.Client.ResourceType.Folder ?
                        Math.round(aHierarchyItems[i].ContentLength / 1000) + ' Kb' :
                        null;
                    console.log(' [' + aHierarchyItems[i].ResourceType + '] ' + aHierarchyItems[i].DisplayName + (sSize ? ', ' + sSize : ''));
                }
            });
        });
    </script>
</head>
<body>
</body>
</html> 

The second parameter used in GetChildrenAsync indicates if immediate children of these folders are requested or the entire subtree.

Creating Folder

To create a folder use Folder.CreateFolderAsync method.

var webDavSession = new ITHit.WebDAV.Client.WebDavSession();
var sFolderAbsolutePath = 'http://localhost:87654/';
var fCallback = function() {};

webDavSession.OpenFolderAsync(sFolderAbsolutePath, null, function(oAsyncResult) {

    /** @typedef {ITHit.WebDAV.Client.Folder} oFolder */
    var oFolder = oAsyncResult.Result;

    oFolder.CreateFolderAsync('my_folder', null, null, function(oAsyncResult) {

        if (oAsyncResult.IsSuccess) {
            /** @typedef {ITHit.WebDAV.Client.Folder} oNewFolder */
            var oNewFolder = oAsyncResult.Result;

            console.log(oNewFolder.Href);
        } else if (oAsyncResult.Error instanceof ITHit.WebDAV.Client.Exceptions.MethodNotAllowedException) {
            console.log('Folder already exists.');
        }

        fCallback(oAsyncResult);
    });
});

Creating a File

To create a file use Folder.CreateFileAsync method. 

var webDavSession = new ITHit.WebDAV.Client.WebDavSession();
var sFolderAbsolutePath = 'http://localhost:87654/';
var fCallback = function() {};

webDavSession.OpenFolderAsync(sFolderAbsolutePath, null, function(oFolderAsyncResult) {

    /** @typedef {ITHit.WebDAV.Client.Folder} oFolder */
    var oFolder = oFolderAsyncResult.Result;

    oFolder.CreateFileAsync('myfile.txt', null, 'Hello World!', null, function(oAsyncResult) {

        /** @typedef {ITHit.WebDAV.Client.File} oFile */
        var oFile = oAsyncResult.Result;

        if (oAsyncResult.Error) {
            console.log(oAsyncResult.toString());
        }

        if (oAsyncResult.IsSuccess) {
            console.log(oFile.DisplayName); // myfile.txt
        }

        fCallback(oAsyncResult);
    });
}); 

Writing File Content

To write file content use File.WriteContentAsync method.

var webDavSession = new ITHit.WebDAV.Client.WebDavSession();
var sFileAbsolutePath = 'http://localhost:87654/myfile.txt';
var fCallback = function() {};

webDavSession.OpenFileAsync(sFileAbsolutePath, null, function(oFileAsyncResult) {

    /** @typedef {ITHit.WebDAV.Client.File} oFile */
    var oFile = oFileAsyncResult.Result;

    oFile.WriteContentAsync('Some content.', null, 'text/plain', function(oAsyncResult) {

        if (oAsyncResult.IsSuccess) {
            console.log('Content is saved!');
        }

        fCallback(oAsyncResult);
    });
}); 

Reading File Content

To read file content use File.ReadContentAsync method.

var webDavSession = new ITHit.WebDAV.Client.WebDavSession();
var sFileAbsolutePath = 'http://localhost:87654/myfile.txt';
var fCallback = function() {};

webDavSession.OpenFileAsync(sFileAbsolutePath, null, function(oFileAsyncResult) {

    /** @typedef {ITHit.WebDAV.Client.File} oFile */
    var oFile = oFileAsyncResult.Result;

    oFile.ReadContentAsync(null, null, function(oAsyncResult) {

        console.log(oAsyncResult.Result);

        fCallback(oAsyncResult);
    });
});

To download only a part of a file, you can specify 2 parameters in the ReadContent call. The First parameter is the starting byte (zero-based) at which to start the content download, the second – amount of bytes to be downloaded. The library will add Range header to the request, in this case.

Checking if Child Item Exists

To verify if the child item exists in the folder use Folder.ItemExistsAsync method.

var webDavSession = new ITHit.WebDAV.Client.WebDavSession();
var sFolderAbsolutePath = 'http://localhost:87654/';
var fCallback = function() {};

webDavSession.OpenFolderAsync(sFolderAbsolutePath, null, function(oAsyncResult) {

    /** @typedef {ITHit.WebDAV.Client.Folder} oFolder */
    var oFolder = oAsyncResult.Result;

    oFolder.ItemExistsAsync('my_folder', function(oAsyncResult) {

        if (oAsyncResult.Result) {
            console.log('Item exists');
        } else {
            console.log('Item not found');
        }

        fCallback(oAsyncResult);
    });
}); 

Copying Items

To copy an item use HierarchyItem.CopyToAsync method. 

var webDavSession = new ITHit.WebDAV.Client.WebDavSession();
var sFolderAbsolutePath = 'http://localhost:87654/Products/';
var sFileAbsolutePath = 'http://localhost:87654/myfile.txt';
var fCallback = function() {};

webDavSession.OpenFileAsync(sFileAbsolutePath, null, function(oFileAsyncResult) {

    /** @typedef {ITHit.WebDAV.Client.File} oFile */
    var oFile = oFileAsyncResult.Result;

    webDavSession.OpenFolderAsync(sFolderAbsolutePath, null, function(oFolderAsyncResult) {

        /** @typedef {ITHit.WebDAV.Client.Folder} oFolder */
        var oFolder = oFolderAsyncResult.Result;

        oFile.CopyToAsync(oFolder, 'myproduct.txt', true, null, null, function(oAsyncResult) {

            if (oAsyncResult.IsSuccess) {
                console.log('Copy successfully completed.');
            } else if (oAsyncResult.Error instanceof ITHit.WebDAV.Client.Exceptions.PreconditionFailedException) {
                console.log('The item with such name exists and `overwrite` was `false`.');
            } else if (oAsyncResult.Error instanceof ITHit.WebDAV.Client.Exceptions.WebDavHttpException) {
                var sErrorText = oAsyncResult.Error.Message + ' ' + oAsyncResult.Error.Status.Code + ' ' +
                    oAsyncResult.Error.Status.Description;

                // Find which items failed to copy.
                for(var i = 0, l = oAsyncResult.Error.Multistatus.Responses.length; i < l; i++) {
                    var oResponse = oAsyncResult.Error.Multistatus.Responses[i];
                    sErrorText += '\n' + oResponse.Href + ' ' + oResponse.Status.Code + ' ' +
                        oResponse.Status.Description;
                }

                console.log('Copy error: ' + sErrorText);
            } else {
                console.log('Copy error: ' + String(oAsyncResult.Error));
            }

            fCallback(oAsyncResult);
        });
    });
});

Moving Items

To move an item use HierarchyItem.MoveToAsync method.

var webDavSession = new ITHit.WebDAV.Client.WebDavSession();
var sDestinationFolderAbsolutePath = 'http://localhost:87654/Sales/';
var sSourceFolderAbsolutePath = 'http://localhost:87654/Products/';
var fCallback = function() {};

webDavSession.OpenFolderAsync(sSourceFolderAbsolutePath, null, function(oSourceFolderAsyncResult) {

    /** @typedef {ITHit.WebDAV.Client.Folder} oSourceFolder */
    var oSourceFolder = oSourceFolderAsyncResult.Result;

    webDavSession.OpenFolderAsync(sDestinationFolderAbsolutePath, null, function(oDestinationFolderAsyncResult) {

        /** @typedef {ITHit.WebDAV.Client.Folder} oDestinationFolder */
        var oDestinationFolder = oDestinationFolderAsyncResult.Result;

        oSourceFolder.MoveToAsync(oDestinationFolder, oSourceFolder.DisplayName, false, null, function(oAsyncResult) {

            if (oAsyncResult.IsSuccess) {
                console.log('Move successfully completed.');
            } else if (oAsyncResult.Error instanceof ITHit.WebDAV.Client.Exceptions.PreconditionFailedException) {
                console.log('The item with such name exists and `overwrite` was `false`.');
            }

            fCallback(oAsyncResult);
        });
    });
}); 

Deleting Items

To delete an item use HierarchyItem.DeleteAsync method.

var webDavSession = new ITHit.WebDAV.Client.WebDavSession();
var sFolderAbsolutePath = 'http://localhost:87654/my_folder/';
var fCallback = function() {};

webDavSession.OpenFolderAsync(sFolderAbsolutePath, null, function(oAsyncResult) {

    /** @typedef {ITHit.WebDAV.Client.Folder} oFolder */
    var oFolder = oAsyncResult.Result;

    oFolder.DeleteAsync(null, function(oAsyncResult) {

        if (oAsyncResult.IsSuccess) {
            console.log('Folder successfully deleted.');
        }

        fCallback(oAsyncResult);
    });
});