Wednesday, November 11, 2020

Show file size documents library SharePoint in Kb, Mb (JQuery)

Due to the closure of "the blog TechNet" I transfer all my articles in the blog :)

You could add JQuery to obtain and display document size into your custom search display template. The code below is about how to show document size beside the document name of all documents uploaded into a SharePoint document library.
You could use the function in the code that obtaining the file size depend on the URL of the document.
You must have the rights to Design web part.

Pre-requisites
SharePoint server 2010, 2013, 2016, 2019.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
function hdrDetails(i, elm, cl) { 
    cl = cl/1024;  //divide content-length by 1024 (KB) 
    var sz = cl>1024?"MB":"KB";  //if cl is still big, set to MB 
    cl = cl>1024?cl/1024:cl;  //if cl is still big, divide again 
    var len = $(elm).eq(i).text().length;  //check the link's text length 
    if(len > 0) { 
        //add a file size 
        $(elm).eq(i).after(" (" + cl.toFixed(2) + " " + sz + ")"); 
    } 
} 
$(function() { 
    var elm="a[href$='.pdf'],"+ //only the file types we want 
	"a[href$='.doc'],"+ 
	"a[href$='.ppt'],"+ 
	"a[href$='.xls'],"+ 
	"a[href$='.docx'],"+
	"a[href$='.pptx'],"+
	"a[href$='.mht'],"+
	"a[href$='.xlsx']"; 
    $(elm).each(function(i, e) { 
        if (e.hostname && e.hostname == location.hostname) { 
            $.ajax({ 
                type: "get", 
                url: $(this).attr("href"), 
                complete: function(xhr, textStatus) { 
                    var cl=xhr.getResponseHeader("content-length"); 
                    hdrDetails(i, elm, cl); //call the calculation fn 			
                } 
            }); 
        } 
    }); 
}); 
</script>

Happy Coding!

No comments:

Post a Comment