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

我需要使用JavaScript打印HTML内的所有文本文件。 我试图修改处理照片的代码,但我没有成功

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

你可以使用<input type="file">设置multiple属性, 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> 

出于安全原因,您无法使用JavaScript访问主机文件系统。 你可以做的最好的做法是做一个单一的Ajax调用服务器端脚本(例如PHP),将收集所有的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); }); 

你可以根据你想要得到的文件types(纯文本或文本/ html或其他)来改变检查MIMEtypes的php行,