HTML/Javascript:迭代本地(服务器端)文件夹的所有元素
基本上,我有一个非常简单的网站,其中根目录如下所示:HTML/Javascript:迭代本地(服务器端)文件夹的所有元素,javascript,html,file-io,directory,Javascript,Html,File Io,Directory,基本上,我有一个非常简单的网站,其中根目录如下所示: /images/ index.html stuff.js 我想以某种方式递归地遍历/images/目录中的每个文件,并在我的网站的某个部分中按顺序显示它们。例如,如果/images/contained: images/a/a.png images/b.png images/c.jpg .... 然后index.html中的某个地方将包含: <img src="images/a/a.png" /> <img src="im
/images/
index.html
stuff.js
我想以某种方式递归地遍历/images/目录中的每个文件,并在我的网站的某个部分中按顺序显示它们。例如,如果/images/contained:
images/a/a.png
images/b.png
images/c.jpg
....
然后index.html中的某个地方将包含:
<img src="images/a/a.png" />
<img src="images/b.png" />
<img src="images/c.jpg" />
....
....
我的第一个想法是使用stuff.js中的document.write()函数来实现这一点,但是我找不到一个好方法来迭代Javascript中的本地文件目录。我看到了一些关于AJAX的内容,但所有这些示例都涉及到编辑现有文件,这显然是我不想做的
我目前的解决方案只是手动创建一个字符串数组,其中包含/images/中的所有文件,但这样做让我觉得“一定有更好的方法!”
如果我不清楚,请告诉我
谢谢 最好的方法可能是使用服务器端语言为您完成,并使用异步Javascript请求显示数据 此示例使用PHP列出指定目录中的所有文件,并使用
xmlhttprequest
加载此输出并将结果转换为图像标记:
getimages.php:
<?php
//The directory (relative to this file) that holds the images
$dir = "Images";
//This array will hold all the image addresses
$result = array();
//Get all the files in the specified directory
$files = scandir($dir);
foreach($files as $file) {
switch(ltrim(strstr($file, '.'), '.')) {
//If the file is an image, add it to the array
case "jpg": case "jpeg":case "png":case "gif":
$result[] = $dir . "/" . $file;
}
}
//Convert the array into JSON
$resultJson = json_encode($result);
//Output the JSON object
//This is what the AJAX request will see
echo($resultJson);
?>
<!DOCTYPE html>
<html>
<head>
<title>Image List Thing</title>
</head>
<body>
<div id="images"></div>
<input type="button" onclick="callForImages()" value="Load" />
<script>
//The div element that will contain the images
var imageContainer = document.getElementById("images");
//Makes an asynch request, loading the getimages.php file
function callForImages() {
//Create the request object
var httpReq = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
//When it loads,
httpReq.onload = function() {
//Convert the result back into JSON
var result = JSON.parse(httpReq.responseText);
//Show the images
loadImages(result);
}
//Request the page
try {
httpReq.open("GET", "getimages.php", true);
httpReq.send(null);
} catch(e) {
console.log(e);
}
}
//Generates the images and sticks them in the container
function loadImages(images) {
//For each image,
for(var i = 0; i < images.length; i++) {
//Make a new image element, setting the source to the source in the array
var newImage = document.createElement("img");
newImage.setAttribute("src", images[i]);
//Add it to the container
imageContainer.appendChild(newImage);
}
}
</script>
</body>
</html>
index.html(与getimages.php目录相同):
<?php
//The directory (relative to this file) that holds the images
$dir = "Images";
//This array will hold all the image addresses
$result = array();
//Get all the files in the specified directory
$files = scandir($dir);
foreach($files as $file) {
switch(ltrim(strstr($file, '.'), '.')) {
//If the file is an image, add it to the array
case "jpg": case "jpeg":case "png":case "gif":
$result[] = $dir . "/" . $file;
}
}
//Convert the array into JSON
$resultJson = json_encode($result);
//Output the JSON object
//This is what the AJAX request will see
echo($resultJson);
?>
<!DOCTYPE html>
<html>
<head>
<title>Image List Thing</title>
</head>
<body>
<div id="images"></div>
<input type="button" onclick="callForImages()" value="Load" />
<script>
//The div element that will contain the images
var imageContainer = document.getElementById("images");
//Makes an asynch request, loading the getimages.php file
function callForImages() {
//Create the request object
var httpReq = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
//When it loads,
httpReq.onload = function() {
//Convert the result back into JSON
var result = JSON.parse(httpReq.responseText);
//Show the images
loadImages(result);
}
//Request the page
try {
httpReq.open("GET", "getimages.php", true);
httpReq.send(null);
} catch(e) {
console.log(e);
}
}
//Generates the images and sticks them in the container
function loadImages(images) {
//For each image,
for(var i = 0; i < images.length; i++) {
//Make a new image element, setting the source to the source in the array
var newImage = document.createElement("img");
newImage.setAttribute("src", images[i]);
//Add it to the container
imageContainer.appendChild(newImage);
}
}
</script>
</body>
</html>
图像列表
//将包含图像的div元素
var imageContainer=document.getElementById(“图像”);
//发出异步请求,加载getimages.php文件
函数callForImages(){
//创建请求对象
var httpReq=(window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject(“Microsoft.XMLHTTP”);
//当它加载时,
httpReq.onload=函数(){
//将结果转换回JSON
var result=JSON.parse(httpReq.responseText);
//显示图像
加载图像(结果);
}
//请求页面
试一试{
open(“GET”,“getimages.php”,true);
httpReq.send(空);
}捕获(e){
控制台日志(e);
}
}
//生成图像并将其粘贴到容器中
函数加载图像(图像){
//对于每个图像,
对于(var i=0;i
请注意,这只是一个示例。您可能希望确保AJAX调用成功,并且JSON转换在服务器代码和客户机上都有效。我偶然发现了这篇文章,因为我正在寻找同样的东西,如何迭代“资源”文件夹中的文件列表,并显示一个网页,其中每个文件都有可单击的快捷方式 以下是我最终得到的网页的一个剪辑: 我是这样做的 我添加了一个非常简单的ASP.Net服务,来遍历这个文件夹中的文件
List<OneResourceFile> listOfFilenames = new List<OneResourceFile>();
string Icon = "";
string localFolder = Server.MapPath("../Resources");
string[] fileEntries = Directory.GetFiles(localFolder);
foreach (string fileName in fileEntries)
{
string filename = System.IO.Path.GetFileName(fileName);
switch (Path.GetExtension(filename).ToLower())
{
case ".pptx":
case ".ppt":
Icon = "cssPowerPoint";
break;
case ".doc":
case ".docx":
Icon = "cssWord";
break;
case ".xlsx":
case ".xlsm":
case ".xls":
Icon = "cssExcel";
break;
default:
Icon = "cssUnknown";
break;
}
OneResourceFile oneFile = new OneResourceFile()
{
Filename = filename,
IconClass = Icon,
URL = "../Resources/" + filename
};
listOfFilenames.Add(oneFile);
}
string JSON = JsonConvert.SerializeObject(listOfFilenames);
return JSON;
…并返回一组JSON结果,如下所示
[
{
Filename: "Mikes Presentation.pptx",
IconClass: "cssPowerPoint",
URL: "~/Resources/Mikes Presentation.pptx"
},
{
Filename: "Mikes Accounts.xlsx",
IconClass: "cssExcel",
URL: "~/Resources/Mikes Accounts.xlsx""
}
]
然后,我得到一些JQuery来调用这个web服务,并为结果中的每个项目创建一个a href
:
<script type="text/javascript">
var URL = "/GetListOfResourceFiles.aspx"; // This is my web service
$.ajax({
url: URL,
type: 'GET',
cache: false,
dataType: "json",
success: function (JSON) {
// We've successfully loaded our JSON data
$.each(JSON.Results, function (inx) {
// Create one <a href> per JSON record, and append it to our list.
var thelink = $('<a>', {
text: this.Filename,
title: this.Filename,
href: this.URL,
class: this.IconClass
}).appendTo('#ListOfResources');
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("$.ajax error: " + xhr.status + " " + thrownError);
}
});
</script>
<p id="ListOfResources">
就这样。很酷,嘿?更好的方法是创建一个Web服务,它检查任何目录的内容并返回一个数组……然后可以通过AJAXI调用该数组。如果您在同一句话中使用“javascript”和“文件I/O”,那么您指的是节点,而不是客户端JS。非常感谢!非常感谢。一个简单的问题:我希望所有这些都自动发生。例如:其中init()的第一行是对callForImages()的调用。我会遇到与此同步的问题吗?也就是说,客户端代码在服务器代码准备好所有信息之前进行调用。@ScoWalt您可以随意调用
callForImages
,不应该遇到任何问题。但是,您可能希望在更新container div元素时清除它。一种快速而混乱的方法是设置它的innerHTML=“
”。在php文件中,您可能需要更改一件事:switch(ltrim(strstrstr($file,'.'),'.')){到switch(strtower)(ltrim(strstrstr($file,'.'),'.')){然后它也会选择.JPG.Jpeg文件,而不仅仅是.Jpeg文件。