1

I need to print all the txt files from a directory inside an HTML using javascript. i tried to modify a code dealing with photos but I didn't success

How to load all the images from one of my folder into my web page, using Jquery/Javascript

var dir = "D:\Finaltests\test1\new\places";
var fileextension = ".txt";
$.ajax({
    //This will retrieve the contents of the folder if the folder is configured as 'browsable'
    url: dir,
    success: function (data) {
        //List all .txt file names in the page
        $(data).find("a:contains(" + fileextension + ")").each(function () {
         var filename = this.href.replace(window.location.host, "").replace("http://", "");
        $("body").append("<input type='file' onload='readText(" + dir + ")>");


        });
    }
});
Community
  • 1
  • 1
user3052503
  • 35
  • 2
  • 12
  • Did you check this http://stackoverflow.com/questions/15537424/get-a-list-of-all-folders-in-directory ? – Chinni Jun 04 '16 at 19:29
  • Path for ajax needs to be a web path, not local file directory path and your page needs to be loading on local server for ajax to work. Server instance will then deliver the file – charlietfl Jun 04 '16 at 19:32
  • thanks for clarification charlietfl , i don't have web path neither a server, what to do? – user3052503 Jun 04 '16 at 19:42

2 Answers2

2

You can use <input type="file"> with multiple attribute set, accept attribute set to text/plain; change event ;FileReader, for loop.

var pre = document.querySelector("pre");

document.querySelector("input[type=file]")
.addEventListener("change", function(event) {
  var files = event.target.files;
  for (var i = 0; i < files.length; i++) {
    (function(file) {
      var reader = new FileReader();
      reader.addEventListener("load", function(e) {
         pre.textContent += "\n" + e.target.result;
      });
      reader.readAsText(file)
    }(files[i]))
  }
})
<input type="file" accept="text/plain" multiple />
<pre>

</pre>

You can also use webkitdirectory and allowdirs attributes for directory upload at chrome, chromium; at nightly 45+ or firefox 42+ where dom.input.dirpicker preference set to true, see Firefox 42 for developers , Select & Drop Files and/or Folders to be parsed. Note, you can also drop folders from file manager at <input type="file"> element

var pre = document.querySelector("pre");

document.querySelector("input[type=file]")
  .addEventListener("change", function(event) {
    console.log(event.target.files)
    var uploadFile = function(file, path) {
      // handle file uploading
      console.log(file, path);
      var reader = new FileReader();
      reader.addEventListener("load", function(e) {
        pre.textContent += "\n" + e.target.result;
      });
      reader.readAsText(file)
    };

    var iterateFilesAndDirs = function(filesAndDirs, path) {
      for (var i = 0; i < filesAndDirs.length; i++) {
        if (typeof filesAndDirs[i].getFilesAndDirectories === 'function') {
          var path = filesAndDirs[i].path;

          // this recursion enables deep traversal of directories
          filesAndDirs[i].getFilesAndDirectories()
          .then(function(subFilesAndDirs) {
            // iterate through files and directories in sub-directory
            iterateFilesAndDirs(subFilesAndDirs, path);
          });
        } else {
          uploadFile(filesAndDirs[i], path);
        }
      }
    };
    if ("getFilesAndDirectories" in event.target) {
      event.target.getFilesAndDirectories()
        .then(function(filesAndDirs) {
          iterateFilesAndDirs(filesAndDirs, '/');
        })
    } else {
      // do webkit stuff
      var files = event.target.files;
      for (var i = 0; i < files.length; i++) {
        (function(file) {
          uploadFile(file)
        }(files[i]))
      }
    }

  })
<!DOCTYPE html>
<html>

<head>
  <script></script>
</head>

<body>
  <input type="file" webkitdirectory allowdirs directory />
  <pre>

</pre>
</body>

</html>

plnkr http://plnkr.co/edit/Y1XYd9rLOdKRHw6tb1Sh?p=preview


For ajax requests at chromium, chrome file: protocol local filesystem you can launch with --allow-file-access-from-files flag set, see Jquery load() only working in firefox?.

At firefox you can set security.fileuri.strict_origin_policy to false, see Security.fileuri.strict origin policy.

For a possible $.ajax() approach at chrome, chromium you can try

var path = "/path/to/drectory"; // `D:\`, `file:///`
var files = [];
$.ajax({url:path, dataType:"text html"})
.then((data) => {
  // match file names from `html` returned by chrome, chromium
  // for directory listing of `D:\Finaltests\test1\new\places`;
  // you can alternatively load the "Index of" document and retrieve
  // `.textContent` from `<a>` elements within `td` at `table` of
  // rendered `html`; note, `RegExp` to match file names
  // could probably be improved,  does not match space characters in file names
  var urls = $.unique(data.match(/\b(\w+|\d+)\.txt\b/g));
  return $.when.apply($, $.map(urls, (file) => {
    files.push(file);
    // `\`, or `/`, depending on filesystem type
    return $.ajax({url:path + "/" + file
                 , dataType:"text html"})
    .then((data) => {
      // return array of objects having property set to `file` name,
      // value set to text within `file`
      return {[file]:data}
    })
  }))
})
.then((...res) => {
  console.log(res, files)
})
guest271314
  • 1
  • 15
  • 104
  • 177
  • the first javascript code returned the content of a choosen file, and the second returned the number of files inside a choosen folder. Is there a way to show the content of a specific directory without choosing? – user3052503 Jun 04 '16 at 21:37
  • @user3052503 _"and the second returned the number of files inside a choosen folder"_ The second example should concatenate text content of selected files to `
    ` element as well. _"Is there a way to show the content of a specific directory without choosing?"_ What do you mean by "the content" and "without choosing"?
    – guest271314 Jun 04 '16 at 21:43
  • "the content" i mean the text content, "without choosing" i mean without selecting a directory when i open the html page. thank you guest271314 for your usefull answers. – user3052503 Jun 04 '16 at 22:04
  • @user3052503 _""the content" i mean the text content, "without choosing" i mean without selecting a directory when i open the html page."_ At chrome, chromium you can try last approach, using `$.get()` – guest271314 Jun 04 '16 at 22:07
  • I guess what i am trying to do is dangerous, i mean it is not safe to --allow-file-access-from-files in chrome. does the last example you wrote need --allow-file-access-from-files? – user3052503 Jun 04 '16 at 22:20
  • 1
    @user3052503 _"does the last example you wrote need --allow-file-access-from-files?"_ Yes, see also updated post for approach to use `XMLHttpRequest()` at local filesystem at firefox – guest271314 Jun 04 '16 at 22:53
  • 1
    what downvote? it is not from me i would like to thank you for your effort with me. – user3052503 Jun 04 '16 at 23:09
  • _see also updated post for approach to use XMLHttpRequest() at local filesystem at firefox_ .Where i can find this post? i just searshed and didn't find it. – user3052503 Jun 04 '16 at 23:19
  • @user3052503 See last approach at current post http://stackoverflow.com/a/37634328/ – guest271314 Jun 04 '16 at 23:31
0

you can't reach the host filesystem with javascript for security reason. The best you can do is to make a single ajax call to a server-side script (php for exemple) that will collect all html file and return them to your ajax call.

gethtml.php:

<?php 


$output = "";

// your list of folders
$folders = [

    'D:\Finaltests\test1\new\places1',
    'D:\Finaltests\test1\old\places2',
    'D:\Finaltests\test1\whatever\places3'
];

foreach ($folders as $key => $dir) {

    if(!is_dir($dir))
        continue;
    // get all files of the directory
    $files = scandir($dir);
    foreach ($files as $file) {

        $finfo = finfo_open(FILEINFO_MIME_TYPE);

        if(finfo_file($finfo, $file) == 'text/plain')
            $output .= file_get_contents($dir . DIRECTORY_SEPARATOR . $file);

    }

}

echo $output;
exit;
 ?>

Ajax call:

$.get('path/to/gethtml.php', function(response){

    $('body').html(response);

});

you can change the line of php that check the mime type according to the type of the file you want to get (plain text or text/html or whatever)

erwan
  • 887
  • 8
  • 17
  • so i need to make several html pages if i have different directories? And then i could gather them in one Html page? – user3052503 Jun 04 '16 at 19:26
  • OP is already attempting to use ajax...this answer is not very concise – charlietfl Jun 04 '16 at 19:30
  • you have differents html pages in differents directory and you want to print all of them in one page right ? If yes, you should write a small server-side script to browser each directory and concatenate the content of each one inside a variable that you will print when finished so that you can make only 1 ajax call and get all your html at a time – erwan Jun 04 '16 at 19:30
  • or i think i could reach children folders. so i just need to put my javascript in a parent folder? var dir = "Src/themes/base/images/"; is Src here a keyword for javascript means this file directory? – user3052503 Jun 04 '16 at 19:33
  • yes, erwan but i still need to get the txt files in my html page – user3052503 Jun 04 '16 at 19:36
  • @user3052503 are you running page from localhost server? If so you need path to be web path to file and server delivers that file. That's the only way ajax will work – charlietfl Jun 04 '16 at 19:37
  • i edited my answer to show you an exemple code that should work (not tested) – erwan Jun 04 '16 at 19:56
  • Thanks erwan, actully i am creating a web page to run only on my computer and i don't want to run a localhost now – user3052503 Jun 04 '16 at 19:59
  • you can't do this with javascript neither with any other web / browser based language. – erwan Jun 04 '16 at 20:28