Wednesday, January 29, 2014

Read files from a folder using jQuery Ajax



All I wanted to do is that I wanted to read images (the filenames) and put them into an image tag
                There is possibility to read a directory using Ajax but before that, my searches lead me to this http://jsfiddle.net/0GiS0/Yvgc2/ and I thought cool
                Except that, I need to put the file names somewhere to read them, then I found this
Very helpful, got me started, but this does not work in a normal scenario
i.e., usual files placed in to a folder next to it won’t work; it needs a server where the directory browsing should be enabled
Let’s go through the steps
Make sure you have IIS or some other web server on your PC
I used IIS 7
Create a folder called reader in C:\inetpub\wwwroot\reader
With that, create another folder call it images and place a few. jpg images in the folder.
C:\inetpub\wwwroot\reader\images
Then create a HTML file called filereadertest.html , with the below code


<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Dir read test</title>
 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
 <script>
 $(document).ready(function(){
      
       var dir = "images";
    var fileextension=".jpg";
      $.ajax({
            url: dir,
            success: function (data) {
                $(data).find("a:contains(" + fileextension + ")").each(function () {
                    var filename = this.href.replace(window.location.host, "").replace("http:///","");  
                    $("#page").append($("<img src=" + filename.replace('reader/','') + "></img>"));
                });
            }
        });
 });
 </script>
</head>
<body>
<div id="page"></div>
</body>
</html>
 
Run internet information services manager (Win+R and type ‘itetmgr’)
With the folder created, you should be able to see it in the website list under default website,
Right click on this folder and select Convert to application

 

After this, select the reader application, and select directory browsing from the features