Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to return a list of all the image file names from a folder using only Javascript?

I want to display all images from folder located in server in image gallery.

Is there a way to return a list of all the image file names from a folder using only JavaScript or JQuery?

Also I want to count the number of image files in similar folder using only JavaScript.

Is there any way to count the number of image files from a folder using only JavaScript?

like image 717
Pooja Avatar asked Aug 09 '11 09:08

Pooja


People also ask

How do you get a list of the names of all files present in a directory in Javascript?

To get a list of the names of all files present in a directory in Node. js, we can call the readdir method. const testFolder = './folder/path'; const fs = require('fs'); fs. readdir(testFolder, (err, files) => { files.

How do I read a directory in node JS?

The fs. readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory. The options argument can be used to change the format in which the files are returned from the method.


1 Answers

No, you can't do this using Javascript alone. Client-side Javascript cannot read the contents of a directory the way I think you're asking about.

However, if you're able to add an index page to (or configure your web server to show an index page for) the images directory and you're serving the Javascript from the same server then you could make an AJAX call to fetch the index and then parse it.

i.e.

1) Enable indexes in Apache for the relevant directory on yoursite.com:

http://www.cyberciti.biz/faq/enabling-apache-file-directory-indexing/

2) Then fetch / parse it with jQuery. You'll have to work out how best to scrape the page and there's almost certainly a more efficient way of fetching the entire list, but an example:

$.ajax({   url: "http://yoursite.com/images/",   success: function(data){      $(data).find("td > a").each(function(){         // will loop through          alert("Found a file: " + $(this).attr("href"));      });   } }); 
like image 190
Euan Avatar answered Oct 09 '22 14:10

Euan