用 Javascript 获取文件夹中的文件名列表

我的网站是从 /assets/photos/文件夹提供了很多图片。如何使用 Javascript 获得该文件夹中的文件列表?

425174 次浏览

当前代码将给出一个文件夹中所有文件的列表,假设它位于服务器端,您希望列出所有文件:

var fs = require('fs');
var files = fs.readdirSync('/assets/photos/');

不,Javascript 不能访问文件系统。服务器端 Javascript是一个完全不同的故事,但我猜你不是那个意思。

对于客户端文件,无法获取用户本地目录中的文件列表。

如果用户提供了上传的文件,您可以通过它们的 input元素访问它们。

<input type="file" name="client-file" id="get-files" multiple />




<script>
var inp = document.getElementById("get-files");
// Access and handle the files


for (i = 0; i < inp.files.length; i++) {
let file = inp.files[i];
// do things with file
}
</script>

我写一个文件 Dir.php

var files = <?php $out = array();
foreach (glob('file/*.html') as $filename) {
$p = pathinfo($filename);
$out[] = $p['filename'];
}
echo json_encode($out); ?>;

在脚本中添加:

<script src='dir.php'></script>

并使用文件[]数组

要获取指定文件夹中的文件名列表,可以使用:

fs.readdir(directory_path, callback_function)

这将返回一个列表,您可以通过简单的列表索引如 file[0],file[1]等进行解析。

我在 Firefox 69.0(在 Ubuntu 上)中使用以下代码读取一个目录,并将图像显示为数码相框的一部分。这个页面是用 HTML、 CSS 和 JavaScript 制作的,它位于我运行浏览器的同一台机器上。这些图像也位于同一台机器上,因此不能从“外部”观看。

var directory = <path>;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', directory, false); // false for synchronous request
xmlHttp.send(null);
var ret = xmlHttp.responseText;
var fileList = ret.split('\n');
for (i = 0; i < fileList.length; i++) {
var fileinfo = fileList[i].split(' ');
if (fileinfo[0] == '201:') {
document.write(fileinfo[1] + "<br>");
document.write('<img src=\"' + directory + fileinfo[1] + '\"/>');
}
}

这要求禁用策略 security.fileuri.strict_origin_policy。这意味着它可能不是您想要使用的解决方案。对我来说,我认为没问题。

我为特定目录中的每个文件制作了不同的路由。因此,进入该路径意味着打开该文件。

function getroutes(list){
list.forEach(function(element) {
app.get("/"+ element,  function(req, res) {
res.sendFile(__dirname + "/public/extracted/" + element);
});
});

我调用这个函数传递目录 __dirname/public/extracted中的文件名列表,它为每个文件名创建了一个不同的路由,我可以在服务器端呈现这个路由。

将 JSONP 应用于 如果还有别的答案:

在/dir.php 中写下以下代码:

<?php
$out = array();
foreach (glob('file/*.html') as $filename) {
$p = pathinfo($filename);
$out[] = $p['filename'];
}
echo 'callback(' . json_encode($out) . ')';
?>

在 index.html 中添加以下脚本:

<script>
/* this function will be fired when there are files
in dir search in php' glob
*/
function callback(files) {
alert(files);
}


/* call inside document.ready to make sure the
callback is already loaded
*/
$(document).ready(function() {
let php = document.createElement("script");
php.setAttribute("src", "/dir.php");
document.body.appendChild(php);
});
</script>

如果使用 nginx,可以设置 autoindex on,然后请求 url,就可以从响应中获得文件名。

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "/assets/photos/", true);
xhttp.send();
}


function myFunction(xml) {
// console.log(xml.responseText)
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(xml.responseText, 'text/html');
var preList = htmlDoc.getElementsByTagName("pre")[0].getElementsByTagName("a")
for (i = 1; i < preList.length; i++) {
console.log(preList[i].innerHTML)
}
}
</script>

我明白这个问题是老问题,但仍然在许多问题上回来。的确,在客户端,您不能使用纯 JavaScript 列出本地目录中的文件。下面是一个完整的代码片段,它使用 PHP 并将文件列表和扩展名传输到 JavaScript。

<?PHP
$out = array();
$out = scandir("MT940");      // Or any path to local dir to be listed
$out = array_diff($out, array('.', '..'));    // Skip current and parent dir
?>


<!DOCTYPE html>
<html lang="pl-PL">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<title></title>
</head>
<body>
<div class="service-container"
data-files= '<?php echo (json_encode($out)); ?>'>
</div>
<script>
let files;
$(document).ready(function() {
$('.service-container').each(function() {
let container = $(this);
files = container.data('files');
fileNames = Object.values(files);
});
});
</script>
  

<!-- Some HTML code here -->
  

<script>
let fileNames = [];
$(document).ready(function() {
console.log(fileNames);
// Do something with fileNames
});
</script>
</body>
</html>

然后检查一个特定的文件,您可以执行 parsedDirectory.includes("filename"),它将返回一个布尔值。

正如其他人的回答表明,在客户端这似乎是不可能的,所以我在服务器端解决了这个问题: 客户和 Js 在一起

get_file(conf.data_address).then(imgs => { // get_file is wrapper of fetch API
let img = new Image();
img.src = `./files/Blackpink/${imgs[0]}`; // e.g. load the first img
img.height = 40;
return new Promise(resolve => {
img.onload = () => {
resolve(img);
}
})
})

服务器端的 django:

def get(self, request): # get method
address = request.query_params.get('address') # get the requested folder
is_database = request.query_params.get('is_database')
if address.endswith('/'):
j = u.get_path_files(address,is_full=False) # wrapper of os.listdir of python to get the files in the requested directory.