如何使用java脚本打印文件夹内的所有txt文件

IT技术 javascript jquery
2021-01-30 07:31:26

我需要使用 javascript 从 HTML 内的目录中打印所有 txt 文件。我试图修改处理照片的代码,但我没有成功

如何使用 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 + ")>");


        });
    }
});
2个回答

您可以使用<input type="file">withmultiple属性集,accept属性设置为text/plain; change事件 ; FileReaderfor循环。

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>


您还可以使用webkitdirectoryallowdirs属性在 chrome、chrome 上进行目录上传;在夜间 45+ 或 firefox 42+,其中dom.input.dirpicker首选项设置为true请参阅 Firefox 42 开发人员选择并删除要解析的文件和/或文件夹请注意,您还可以从文件管理器中的<input type="file">元素中删除文件夹

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


对于可以在设置标志的情况下启动的ajaxchrome、chromefile:协议本地文件系统的请求--allow-file-access-from-files,请参阅仅在firefox 中工作的Jquery load()?.

在 Firefox 中,您可以设置security.fileuri.strict_origin_policyfalse,请参阅Security.fileuri.strict origin policy

对于$.ajax()的可能方法,您可以尝试使用铬

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)
})
@user3052503 “你写的最后一个例子需要--allow-file-access-from-files吗?” 是的,另请参阅更新的帖子以了解XMLHttpRequest()在 Firefox 的本地文件系统中使用的方法
2021-03-27 07:31:26
第一个 javascript 代码返回所选文件的内容,第二个返回所选文件夹内的文件数。有没有办法在不选择的情况下显示特定目录的内容?
2021-03-30 07:31:26
@ user3052503 “第二个返回所选文件夹内的文件数”第二个示例也应将所选文件的文本内容连接到<pre>元素。“有没有办法不选择就显示特定目录的内容?” “内容”和“不选择”是什么意思?
2021-03-30 07:31:26
什么downvote?这不是来自我,我要感谢你为我所做的努力。
2021-04-02 07:31:26
“内容”是指文本内容,“不选择”是指在打开 html 页面时不选择目录。感谢guest271314 提供有用的答案。
2021-04-10 07:31:26

出于安全原因,您无法使用 javascript 访问主机文件系统。您能做的最好的事情是对服务器端脚本(例如 php)进行一次 ajax 调用,该脚本将收集所有 html 文件并将它们返回给您的 ajax 调用。

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调用:

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

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

});

您可以根据要获取的文件类型(纯文本或文本/html 或其他)更改检查 mime 类型的 php 行

所以如果我有不同的目录,我需要制作几个html页面吗?然后我可以将它们收集在一个 Html 页面中?
2021-03-16 07:31:26
您在不同的目录中有不同的 html 页面,并且您想在一页中打印所有这些页面,对吗?如果是,您应该编写一个小的服务器端脚本来浏览每个目录,并将每个目录的内容连接到一个变量中,完成后将打印该变量,以便您一次只能进行 1 次 ajax 调用并获取所有 html
2021-03-20 07:31:26
是的,erwan 但我仍然需要在我的 html 页面中获取 txt 文件
2021-03-20 07:31:26
OP 已经在尝试使用 ajax...这个答案不是很简洁
2021-04-06 07:31:26
或者我想我可以拿到儿童文件夹。所以我只需要将我的 javascript 放在父文件夹中?var dir = "src/themes/base/images/"; 这里的 Src 是 javascript 的关键字,意思是这个文件目录吗?
2021-04-12 07:31:26