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
我需要使用javascript从HTML内的目录中打印所有txt文件。我试图修改一个处理照片的代码,但是我没有成功。
How to load all the images from one of my folder into my web page, using Jquery/Javascript
如何使用Jquery/Javascript将文件夹中的所有图像加载到web页面中
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 个解决方案
#1
3
You can use <input type="file">
with multiple
attribute set, accept
attribute set to text/plain
; change
event ;FileReader
, for
loop.
可以使用与多个属性集,接受属性集为text/plain;更改事件;FileReader, for循环。
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
你也可以使用webkitdirectory和allowdirs属性的目录上传在chrome, chromium;在每晚45+或firefox42 +的位置输入。dirpicker首选项设置为true,请参阅Firefox 42,选择并删除要解析的文件和/或文件夹。注意,您还可以在元素下拉文件夹
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
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?.
对于chromium上的ajax请求,chrome file:协议本地文件系统,您可以使用—allow-file-access-from-files标志进行启动,请参见仅在firefox中工作的Jquery load()。
At firefox you can set security.fileuri.strict_origin_policy
to false
, see Security.fileuri.strict origin policy
.
在firefox中,可以设置security.fileuri。strict_origin_policy为false,请参见Security.fileuri。严格的政策。
For a possible $.ajax()
approach at chrome, chromium you can try
对于chrome的一种可能的$.ajax()方法,可以尝试chromium
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)
})
#2
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.
出于安全原因,您无法使用javascript访问主机文件系统。最好的方法是对服务器端脚本(例如php)进行一次ajax调用,该脚本将收集所有html文件并将其返回给ajax调用。
gethtml.php:
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:
Ajax调用:
$.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)
可以根据要获取的文件的类型更改检查mime类型的php行(纯文本或文本/html或其他)
#1
3
You can use <input type="file">
with multiple
attribute set, accept
attribute set to text/plain
; change
event ;FileReader
, for
loop.
可以使用与多个属性集,接受属性集为text/plain;更改事件;FileReader, for循环。
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
你也可以使用webkitdirectory和allowdirs属性的目录上传在chrome, chromium;在每晚45+或firefox42 +的位置输入。dirpicker首选项设置为true,请参阅Firefox 42,选择并删除要解析的文件和/或文件夹。注意,您还可以在元素下拉文件夹
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
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?.
对于chromium上的ajax请求,chrome file:协议本地文件系统,您可以使用—allow-file-access-from-files标志进行启动,请参见仅在firefox中工作的Jquery load()。
At firefox you can set security.fileuri.strict_origin_policy
to false
, see Security.fileuri.strict origin policy
.
在firefox中,可以设置security.fileuri。strict_origin_policy为false,请参见Security.fileuri。严格的政策。
For a possible $.ajax()
approach at chrome, chromium you can try
对于chrome的一种可能的$.ajax()方法,可以尝试chromium
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)
})
#2
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.
出于安全原因,您无法使用javascript访问主机文件系统。最好的方法是对服务器端脚本(例如php)进行一次ajax调用,该脚本将收集所有html文件并将其返回给ajax调用。
gethtml.php:
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:
Ajax调用:
$.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)
可以根据要获取的文件的类型更改检查mime类型的php行(纯文本或文本/html或其他)