How to get the number of images in a folder with Javascript/Jquery

Asked

Viewed 1,394 times

0

I tried to use this function:

function getCount(foldername)
    {
      var myObject, f, filesCount;
      myObject = new ActiveXObject("Scripting.FileSystemObject");
      f = myObject.GetFolder(foldername);
      filesCount = f.files.Count;
      document.write("The number of files in this folder is: " + filesCount);
    }

However, I get the error: Uncaught Referenceerror: Activexobject is not defined

Does anyone know an effective way to get the total number of image files from a folder with Javascript/Jquery? To make it easier, it can be counting everything in the folder, because there is no possibility of another file type other than image.

  • In which browser are you trying to run this?

  • Error occurs in Chrome.

  • I will venture to say that not because Javascript is a client side language, these images you want to count will be on the server (although while you are developing it is in a folder on the computer). Maybe it’s possible with ajax, maybe...

  • Because it is...I realized that Ajax would be the correct option since it can perform request for a beckend code, but how would this interaction?

  • http://answall.com/questions/493/retornar-array-com-nome-de-todos-os-arquivos-em-diret%C3%B3rio

  • Activex is a proprietary framework and works (badly) only in Internet Explorer. Stay away from it.

Show 1 more comment

1 answer

1

It is not possible to do with client-side Javascript, as the browser cannot have access to computer files (except in specific situations such as file uploads).

If you need to count the files on client-side, you can make a extension for Chrome, knowing that it will only work in this browser.

If you need to count the files on the server, you will need to use a language server-side like PHP, Python, Ruby, or even Javascript itself with Node.js. For example, in PHP it would look like this:

$fi = new FilesystemIterator('/caminho/para/a/pasta');
echo "Quantidade de arquivos: " .iterator_count($fi);
  • Good answer, but is it impossible even with Ajax?

  • If you have the directory listing enabled, you can get this page via AJAX and count the files with Javascript, as demonstrated in the @Maicon linked response. However, this is a practice not recommended for security reasons, as you will make public all the contents of a server folder.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.