jquerydirectorydirectory-listing

Get filenames in a given directory jQuery


I'd like to get a list of filenames that will later be stored into an array. The following code just displays directory listing in the same way Apache listing is displayed in a browser, e. g. 1234.txt 31-Aug-2016 13:17 35K How to change it, so I get just the filenames?

<script type="text/javascript">
$(document).ready(function () {
  $.get("dat/", function(data) {
    $("#files").append(data);
  });
});
</script>
<body>
<div id='files'></div>
</body>

Solution

  • Please try with below code. openFile function is useful to check whether it is file or folder. Please add more extensions in function as per your use.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script>
        var fileNames = new Array();
        $.ajax({
          url: "/test/",
          success: function(data){
             $(data).find("td > a").each(function(){
                if(openFile($(this).attr("href"))){
                    fileNames.push($(this).attr("href"));
                }           
             });
          }
        }); 
        console.log(fileNames);
        function openFile(file) {
            var extension = file.substr( (file.lastIndexOf('.') +1) );
            switch(extension) {
                case 'jpg':
                case 'png':
                case 'gif':   // the alert ended with pdf instead of gif.
                case 'zip':
                case 'rar':
                case 'pdf':
                case 'php':
                case 'doc':
                case 'docx':
                case 'xls':
                case 'xlsx':
                    return true;
                default:
                    return false;
            }
        };
    </script>