zoukankan      html  css  js  c++  java
  • UNLIMITED FILES AND FOLDERS HIERARCHY IN SHAREPOINT ONLINE USING REST API

    INTRODUCTION:

    In this blog post, I will provide you a way to create tree view hierarchy of your SharePoint library content. And because it is based on SharePoint REST API, you can use this trick for on-premise SharePoint and also SharePoint online.

    PROBLEM STATEMENT:

    One of my clients has many levels of folders and files created by their end users. They often get into trouble to find specific folder to see the files inside that folder. They asked for help!

    SOLUTION:

    After some thoughts, I have come up with a generic algorithm to find files/ folders hierarchy up to any level using REST API in Office 365/ SharePoint 2013.

    On selection of any library all the files and folders below them will be displayed in a hierarchical manner.

    folder hierarchy 1

    folder hierarchy 2

    DETAILED STEPS:

    STEP 1 – ADD JQUERY FILE REFERENCE TO THE PAGE:

    <script type="text/javascript" src="https://sharepointjunkies.sharepoint.com/sites/demo/Style Library/jquery-1.9.1.js"></script>

    STEP 2 – ADD BELOW HTML TAGS (READ COMMENTS FOR EXPLANATION):

    <!--To Populate Libraries-->
    <select id="drpSelectSourceLibrary"></select>
    
    <!--To Populate Levels on click-->
    <input class="getLevels" name="getLevels" type="button" value="Get Levels" onclick="return false;" />
    
    <!--To Populate Hidden Levels-->
    <div class="genHier"></div>
    
    <hr />
    
    <!--To Populate Hierarchy Visible on page-->
    <div class="dupHenHier"></div>

    STEP 3 – ADD BELOW STYLES TO THE PAGE

    It Is to make buttons and drop down look prettier:

    <style>
        input[type=button] {
            background: #ccc;
            border: 0 none;
            cursor: pointer;
            -webkit-border-radius: 0px;
            border-radius: 0px;
            margin-left: 0px !important;
            font-size: small;
            font-weight: bold;
        }
    
        .dupHier img {
            padding-right: 10px;
        }
    
        .dupHier a {
            position: relative;
            top: -2px;
        }
    
        .dupHier {
            padding-top: 5px;
            padding-bottom: 5px;
        }
    </style>

    STEP 4 – UPLOAD ICONS

    Upload two icons to the style library, one for file and other for folder. It should be 16px by 16px.

    STEP 5

    Now, the page should be ready with placeholders. Next step is to create actual hierarchy of files & folders coming from selected library. Below is the algorithm with explanation:

    • Populate all the libraries in the drop down (Refer: //Population of libraries in the code)

    folder hierarchy 3

    • Get all the files and folders with the help of single REST call
    var certURL = appWebUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$expand=Folder,File&$select=ID,Title,FileLeafRef,Folder/ServerRelativeUrl";
    • Create object to store levels and determine whether current item is file or folder
    function hierMaker(name, path, level, isFile) 
    {
             this.name = name; //Name of file, folder
             this.path = path; //File path
             this.level = level; //Levels in the folder hierarchy like 0, 1, 2, 3……
             this.isFile = isFile; //Whether it is file or folder
    }
    • Iterate through all the results of the above REST call to store all the data to a global object.
    var hmsc = new hierMaker(data[i].FileLeafRef, path, level, isFile);
    hm.push(hmsc);
    • Refer a dummy HTML tag to store all the results. It will be hidden on the page. The idea is to iterate through this dummy HTML element which will have all the records but not in any specific order. We will use this hidden container to populate all the ordered records.
    • Iterate through all the elements of global object and create JUST LEVEL 0 elements and assign to a visible HTML div on page. We need level 0 just to initialize the recursion, level 0 elements will bring level 1 element inside, level 1 will bring level 2 and so on….

    Refer code: //Creation of level 0 elements

    • Iterate through level 0 elements and fill level 1 elements below to respective parent
    • Make the call recursive to fill level 2 below level 1, so on //Call(); method is used to fill child below levels
    • Provide appropriate padding to the html elements as per the level to give hierarchical look and feel. //Provide padding as per level, padding è level * 10px

    STEP 6

    Refer to the completed code below (use a text file and add to the page using content editor web part):

    <script type="text/javascript" src="https://sharepointjunkies.sharepoint.com/sites/demo/Style Library/jquery-1.9.1.js"></script>
    
    <style>
        input[type=button] {
            background: #ccc;
            border: 0 none;
            cursor: pointer;
            -webkit-border-radius: 0px;
            border-radius: 0px;
            margin-left: 0px !important;
            font-size: small;
            font-weight: bold;
        }
    
        .dupHier img {
            padding-right: 10px;
        }
    
        .dupHier a {
            position: relative;
            top: -2px;
        }
    
        .dupHier {
            padding-top: 5px;
            padding-bottom: 5px;
        }
    </style>
    
    <!--To Populate Libraries-->
    <select id="drpSelectSourceLibrary"></select>
    
    <!--To Populate Levels on click-->
    <input class="getLevels" name="getLevels" type="button" value="Get Levels" onclick="return false;" />
    
    <!--To Populate Hidden Levels-->
    <div class="genHier"></div>
    
    <hr />
    
    <!--To Populate Hierarchy Visible on page-->
    <div class="dupHenHier"></div>
    
    <script type="text/javascript">
    
        //Site Context URL
        var spctx = _spPageContextInfo.siteAbsoluteUrl;
    
        //Array to Store all the objects
        var hm = [];
    
        //Object involving File/Folder name, path, level in hierarchy, whether it is file or folder
        function hierMaker(name, path, level, isFile) {
            this.name = name;
            this.path = path;
            this.level = level;
            this.isFile = isFile;
        }
    
        var virtualLevel = 0;
        var boolVirtual = true;
        var maxLevel = 0;
        function getLevels() {
    
            //Reset global variables
            hm.length = 0;
            virtualLevel = 0;
            boolVirtual = true;
            maxLevel = 0;
            tctr = 1;
            $('.genHier').html("");
            $('.dupHenHier').html("");
    
            //Main code below
            var appWebUrl = spctx;
            var listName = $("#drpSelectSourceLibrary option:selected").text();
            var certURL = appWebUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$expand=Folder,File&$select=ID,Title,FileLeafRef,Folder/ServerRelativeUrl";
            $.ajax({
                url: certURL,
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: function (data) {
                    getFolderSchema(data.d.results);
                },
                error: function (data) {
                    alert(JSON.stringify(data));
                }
            });
    
            function getFolderSchema(data) {
                maxLevel = 0;
                dLength = data.length;
                if (dLength >= 0) {
                    for (var i = 0; i < dLength; i++) {
                        if (boolVirtual) {
    
                            if (data[i].Folder.ServerRelativeUrl) {
                                virtualLevel = data[i].Folder.ServerRelativeUrl.split('/').length;
                                boolVirtual = false;
                            }
                            else {
                                virtualLevel = data[i].File.ServerRelativeUrl.split('/').length;
                                boolVirtual = false;
                            }
                        }
                        var isFile = false;
                        var path = "";
                        var level = 0;
                        if (data[i].Folder.ServerRelativeUrl) {
                            //It is folder
                            isFile = false;
                            path = data[i].Folder.ServerRelativeUrl;
                            level = data[i].Folder.ServerRelativeUrl.split('/').length - virtualLevel;
                        }
                        else {
                            //It is file
                            isFile = true;
                            path = data[i].File.ServerRelativeUrl;
                            level = data[i].File.ServerRelativeUrl.split('/').length - virtualLevel;
                        }
                        var tmpDiv = "<div class='subHier' isFile='" + isFile + "' level='" + level + "' path='" + path + "'><a  href='" + path + "' target='_blank'>" + data[i].FileLeafRef + "</a></div>";
                        $(".genHier").append(tmpDiv);
                        maxLevel++;
    
                        var hmsc = new hierMaker(data[i].FileLeafRef, path, level, isFile);
                        hm.push(hmsc);
                    }
                    providePaddding();
                }
    
            }
    
        }
    
    
        var d = 1;
        function providePaddding() {
            var kickCtr = 0;
            var hmlength = hm.length;
            for (var j = 0; j < hmlength; j++) {
                //Creation of level 0 elements
                if (hm[j].level == 0) {
                    var tmpDiv = "";
                    if (hm[j].isFile) {
                        tmpDiv = "<div class='dupHier' isFile='" + hm[j].isFile + "' level='" + hm[j].level + "' path='" + hm[j].path + "'><img src='" + file + "' /><a  href='" + hm[j].path + "' target='_blank'>" + hm[j].name + "</a></div>";
                    }
                    else {
                        tmpDiv = "<div class='dupHier' isFile='" + hm[j].isFile + "' level='" + hm[j].level + "' path='" + hm[j].path + "'><img src='" + folder + "' /><a  href='" + hm[j].path + "' target='_blank'>" + hm[j].name + "</a></div>";
                    }
    
                    kickCtr++;
                    $('.dupHenHier').append(tmpDiv);
                }
            }
    
            call();
    
        }
    
    
        var tctr = 1;
        var folder = spctx + "/Style Library/folder.png";
        var file = spctx + "/Style Library/file.png";
        function call() {
            $('.dupHier').each(function () {
                if ($(this).attr('isDone')) {
                    //continue;
                }
                else {
                    for (var j = 0; j < hm.length; j++) {
                        if (hm[j].level == tctr) {
                            var str = hm[j].path + "";
                            var ts = $(this).attr('path');
                            var tmpDiv = "";
                            if (str.indexOf(ts) > -1) {
    
                                if (hm[j].isFile) {
                                    tmpDiv = "<div class='dupHier' isFile='" + hm[j].isFile + "' level='" + hm[j].level + "' path='" + hm[j].path + "'><img src='" + file + "'/><a  href='" + hm[j].path + "' target='_blank'>" + hm[j].name + "</a></div>";
                                }
                                else {
                                    tmpDiv = "<div class='dupHier' isFile='" + hm[j].isFile + "' level='" + hm[j].level + "' path='" + hm[j].path + "'><img src='" + folder + "'/><a  href='" + hm[j].path + "' target='_blank'>" + hm[j].name + "</a></div>";
                                }
    
                                $(this).append(tmpDiv);
                            }
                        }
                    }
                }
                $(this).attr('isDone', true);
            });
    
            tctr++;
            if (tctr < 10)
                call();
            //Provide padding as per level, level * 10px
            $('.dupHier').each(function () {
                var tmpPad = $(this).attr('level') * 10 + "px";
                $(this).css({ "padding-left": tmpPad });
            });
    
        }
    
        $(document).ready(function () {
            $('.getLevels').click(function () {
                getLevels();
            });
    
            $('.genHier').hide();
        });
    
        //Population of libraries
        ExecuteOrDelayUntilScriptLoaded(loadDocLibraries, "SP.js");
        function loadDocLibraries() {       
            var clientContext = new SP.ClientContext.get_current();
            web = clientContext.get_web();
            clientContext.load(web);
            listColl = web.get_lists();
            clientContext.load(listColl);
            clientContext.executeQueryAsync(onLibSuccess, onLibfail);
    
        }
        function onLibSuccess() {
            var listEnumerator = listColl.getEnumerator();
            var Lib = "";
            $('#drpSelectSourceLibrary').empty();
            $("#drpSelectSourceLibrary").prepend('<option value="Select" selected="selected">Select Documents Library</option>');
    
    
            while (listEnumerator.moveNext()) {
                var list = listEnumerator.get_current();
                var value = list.get_hidden();
                //console.log(value);
                if (list.get_baseTemplate() == '101') {
                    if (value == false) {
    
                        var x = document.getElementById("drpSelectSourceLibrary");
                        var option = document.createElement("option");
    
                        var filename = list.get_title();
    
                        option.text = filename;
                        x.add(option);
    
                    }
    
                }
            }
    
        }
    
        function onLibfail() {
            console.log(arguments[1].get_message());
        }
    </script>

    原文地址:http://www.sharepointjunkies.com/unlimited-files-folders-hierarchy-sharepoint-online-using-rest-api/

  • 相关阅读:
    各种web页面中的绘图技术对比
    32位和64位操作系统
    mysql新建用户本地无法登录
    ruby libmysqlclient.18.dylib
    jenkins创建git任务连接时遇到的问题
    mybatis 打印日志log4j.properties
    使用shell统计出出现次数排名top10的网址(在博客园中没找到,特转一下)
    ActiveMQ和Tomcat的整合应用(转)
    java 哪些情况下会使对象锁释放
    Web容器与Servlet
  • 原文地址:https://www.cnblogs.com/bjdc/p/10943282.html
Copyright © 2011-2022 走看看