2

i want t get the number of files in a folder. there are many images in my folder i want to count there numbers is there any way to do that using jquery or javascript ? Thanks in advance

3
  • 2
    Only the server can determine the contents in it. You'll have to make a XHR-call to the backend, counting the files and returning the response. Commented Mar 24, 2015 at 12:02
  • Only Node.js can do this for your. jQuery is a client side framework. Commented Mar 24, 2015 at 12:04
  • that folder is in your local machine or server? Commented Mar 24, 2015 at 12:30

3 Answers 3

4

If the server is Apache and Directory Listing is allowed, and you AJAX' a directory, Apache will typically return a document with a <table> containing the files in the directory if there is no index files present. You can extract the <table> from the document and show it, or count the number of rows in the table containing file information. I would consider any row in that table having a size column with value 0 or higher as a file.

markup :

<div id="fileCount"></div>
<div id="files"></div>

ajax:

$.ajax({
    url: "images/",
    success: function(data) {
        var parser = new DOMParser(),
            doc = parser.parseFromString(data, 'text/html');

        //output the file table
        $("#files").append(doc.querySelector('table').outerHTML);

        //or return the number of files
        //tr = icon, filename, date, size, desc
        //consider all rows with a size value holding a number as a vlid file
        var fileCount = 0,
            rows = doc.querySelector('table').querySelectorAll('tr');

        for (var i=0;i<rows.length;i++) {
            if (rows[i].children[3]) {
                if (parseInt(rows[i].children[3].innerText)>0) fileCount++;         
            }
        }
        $("#fileCount").text(fileCount+' files');
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer. Although, I had to use .children[2]
1

I didn't tried yet, but could be like this.

$.ajax({
    url: "/images-folder-on-server/",
    success: function (data) {
        var image_count = $(data).length();     
    }
});

Comments

-1

JavaScript is client side language. it not allowed to access file to server, if you are using ASP.net then use below line of code for get count of file.

IO.Directory.GetFiles("\translated\path","27_*.jpg").Count()

2 Comments

aps.net? you meant asp.net?
I've to open files which is on client side but I believe you can't directly open until you browse it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.