如何使用 Jquery/Javascript 将我的一个文件夹中的所有图像加载到我的网页中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18480550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to load all the images from one of my folder into my web page, using Jquery/Javascript
提问by rishy
I have a folder named "images" in the same directory as my .js file. I want to load all the images from "images" folder into my html page using Jquery/Javascript.
我在与我的 .js 文件相同的目录中有一个名为“images”的文件夹。我想使用 Jquery/Javascript 将“图像”文件夹中的所有图像加载到我的 html 页面中。
Since, names of images are not some successive integers, how am I supposed to load these images?
由于图像的名称不是一些连续的整数,我应该如何加载这些图像?
回答by Roko C. Buljan
Works both localhost and on live server without issues, and allows you to extend the delimited list of allowed file-extensions:
在本地主机和实时服务器上都可以正常工作,并且允许您扩展允许的文件扩展名的分隔列表:
var folder = "images/";
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
$("body").append( "<img src='"+ folder + val +"'>" );
}
});
}
});
NOTICE
注意
Apacheserver has Option Indexes
turned on by default - if you use another server like i.e. Express for Nodeyou could use this NPM package for the above to work: https://github.com/expressjs/serve-index
Option Indexes
默认情况下Apache服务器已打开 - 如果您使用另一台服务器,例如Express for Node,您可以使用此 NPM 包使上述工作:https: //github.com/expressjs/serve-index
If the files you want to get listed are in /images
than inside your server.js you could add something like:
如果您要列出的文件/images
不在 server.js 中,您可以添加如下内容:
const express = require('express');
const app = express();
const path = require('path');
// Allow assets directory listings
const serveIndex = require('serve-index');
app.use('/images', serveIndex(path.join(__dirname, '/images')));
回答by Roy M J
Use :
用 :
var dir = "Src/themes/base/images/";
var fileextension = ".png";
$.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: dir,
success: function (data) {
//List all .png file names in the page
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<img src='" + dir + filename + "'>");
});
}
});
If you have other extensions, you can make it an array and then go through that one by one using in_array()
.
如果您有其他扩展名,您可以将其设为一个数组,然后使用in_array()
.
P.s : The above source code is not tested.
ps:以上源码未经测试。
回答by Bart Hoekstra
This is the way to add more file extentions, in the example given by Roy M J in the top of this page.
这是添加更多文件扩展名的方法,在本页顶部 Roy MJ 给出的示例中。
var fileextension = [".png", ".jpg"];
$(data).find("a:contains(" + (fileextension[0]) + "), a:contains(" + (fileextension[1]) + ")").each(function () { // here comes the rest of the function made by Roy M J
In this example I have added more contains.
在这个例子中,我添加了更多的包含。
回答by Pnar Sbi Wer
Here is one way to do it. Involves doing a little PHP as well.
这是一种方法。也涉及做一点 PHP。
The PHP part:
PHP部分:
$filenameArray = [];
$handle = opendir(dirname(realpath(__FILE__)).'/images/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
array_push($filenameArray, "images/$file");
}
}
echo json_encode($filenameArray);
The jQuery part:
jQuery 部分:
$.ajax({
url: "getImages.php",
dataType: "json",
success: function (data) {
$.each(data, function(i,filename) {
$('#imageDiv').prepend('<img src="'+ filename +'"><br>');
});
}
});
So basically you do a PHP file to return you the list of image filenames as JSON, grab that JSON using an ajax call, and prepend/append them to the html. You would probably want to filter the files u grab from the folder.
所以基本上你做一个 PHP 文件以将图像文件名列表返回为 JSON,使用 ajax 调用获取该 JSON,并将它们添加/附加到 html。您可能想要过滤从文件夹中抓取的文件。
Had some help on the php part from 1
从1开始对 php 部分有一些帮助
回答by Rainman
If interested in doing this without jQuery - here's a pure JS variant (from here) of the answer currently most upvoted:
如果有兴趣在没有 jQuery 的情况下执行此操作 - 这是目前最受好评的答案的纯 JS 变体(来自此处):
var xhr = new XMLHttpRequest();
xhr.open("GET", "/img", true);
xhr.responseType = 'document';
xhr.onload = () => {
if (xhr.status === 200) {
var elements = xhr.response.getElementsByTagName("a");
for (x of elements) {
if ( x.href.match(/\.(jpe?g|png|gif)$/) ) {
let img = document.createElement("img");
img.src = x.href;
document.body.appendChild(img);
}
};
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
}
xhr.send()
回答by MrFlamey
If, as in my case, you would like to load the images from a local folder on your own machine, then there is a simple way to do it with a very short Windows batch file. This uses the ability to send the output of any command to a file using > (to overwrite a file) and >> (to append to a file).
如果像我一样,您想从自己机器上的本地文件夹加载图像,那么有一种简单的方法可以使用非常短的 Windows 批处理文件来完成。这使用了使用>(覆盖文件)和>>(附加到文件)将任何命令的输出发送到文件的能力。
Potentially, you could output a list of filenames to a plain text file like this:
可能,您可以将文件名列表输出到纯文本文件,如下所示:
dir /B > filenames.txt
However, reading in a text file requires more faffing around, so I output a javascript file instead, which can then be loaded in your to create a global variable with all the filenames in it.
但是,读取文本文件需要更多的处理,所以我输出一个 javascript 文件,然后可以将其加载到您的文件中以创建一个包含所有文件名的全局变量。
echo var g_FOLDER_CONTENTS = mlString(function() { /*! > folder_contents.js
dir /B images >> folder_contents.js
echo */}); >> folder_contents.js
The reason for the weird function with comment inside notation is to get around the limitation on multi-line strings in Javascript. The output of the dir command cannot be formatted to write a correct string, so I found a workaround here.
使用带有注释的奇怪函数的原因是为了绕过 Javascript 中多行字符串的限制。dir 命令的输出无法格式化以写入正确的字符串,因此我在这里找到了解决方法。
function mlString(f) {
return f.toString().
replace(/^[^\/]+\/\*!?/, '').
replace(/\*\/[^\/]+$/, '');
}
Add this in your main code before the generated javascript file is run, and then you will have a global variable called g_FOLDER_CONTENTS, which is a string containing the output from the dir command. This can then be tokenized and you'll have a list of filenames, with which you can do what you like.
在运行生成的 javascript 文件之前将其添加到您的主代码中,然后您将拥有一个名为 g_FOLDER_CONTENTS 的全局变量,它是一个包含 dir 命令输出的字符串。然后可以将其标记化,您将拥有一个文件名列表,您可以使用它来做您喜欢的事情。
var filenames = g_FOLDER_CONTENTS.match(/\S+/g);
Here's an example of it all put together: image_loader.zip
下面是一个例子:image_loader.zip
In the example, run.batgenerates the Javascript file and opens index.html, so you needn't open index.html yourself.
在示例中,run.bat生成 Javascript 文件并打开 index.html,因此您无需自己打开 index.html。
NOTE: .bat is an executable type in Windows, so open them in a text editor before running if you are downloading from some random internet link like this one.
注意:.bat 是 Windows 中的一种可执行类型,因此如果您是从像这样的随机互联网链接下载,请在运行之前在文本编辑器中打开它们。
If you are running Linux or OSX, you can probably do something similar to the batch file and produce a correctly formatted javascript string without any of the mlString faff.
如果您运行的是 Linux 或 OSX,您可能可以执行类似于批处理文件的操作,并生成格式正确的 javascript 字符串,而无需任何 mlString faff。
回答by Siva Shanmugam
$(document).ready(function(){
var dir = "test/"; // folder location
var fileextension = ".jpg"; // image format
var i = "1";
$(function imageloop(){
$("<img />").attr('src', dir + i + fileextension ).appendTo(".testing");
if (i==13){
alert('loaded');
}
else{
i++;
imageloop();
};
});
});
For this script, I have named my image files in a folder as 1.jpg
, 2.jpg
, 3.jpg
, ... to 13.jpg
.
对于此脚本,我将文件夹中的图像文件命名为1.jpg
, 2.jpg
, 3.jpg
, ... to 13.jpg
。
You can change directory and file names as you wish.
您可以根据需要更改目录和文件名。
回答by ashish
Based on the answer of Roko C. Buljan, I have created this method which gets images from a folder and its subfolders. This might need some error handling but works fine for a simple folder structure.
根据 Roko C. Buljan 的回答,我创建了这种从文件夹及其子文件夹中获取图像的方法。这可能需要一些错误处理,但适用于简单的文件夹结构。
var findImages = function(){
var parentDir = "./Resource/materials/";
var fileCrowler = function(data){
var titlestr = $(data).filter('title').text();
// "Directory listing for /Resource/materials/xxx"
var thisDirectory = titlestr.slice(titlestr.indexOf('/'), titlestr.length)
//List all image file names in the page
$(data).find("a").attr("href", function (i, filename) {
if( filename.match(/\.(jpe?g|png|gif)$/) ) {
var fileNameWOExtension = filename.slice(0, filename.lastIndexOf('.'))
var img_html = "<img src='{0}' id='{1}' alt='{2}' width='75' height='75' hspace='2' vspace='2' onclick='onImageSelection(this);'>".format(thisDirectory + filename, fileNameWOExtension, fileNameWOExtension);
$("#image_pane").append(img_html);
}
else{
$.ajax({
url: thisDirectory + filename,
success: fileCrowler
});
}
});}
$.ajax({
url: parentDir,
success: fileCrowler
});
}
回答by Suraj Lulla
Add the following script:
添加以下脚本:
<script type="text/javascript">
function mlString(f) {
return f.toString().
replace(/^[^\/]+\/\*!?/, '');
replace(/\*\/[^\/]+$/, '');
}
function run_onload() {
console.log("Sample text for console");
var filenames = g_FOLDER_CONTENTS.match(/\S+/g);
var fragment = document.createDocumentFragment();
for (var i = 0; i < filenames.length; ++i) {
var extension = filenames[i].substring(filenames[i].length-3);
if (extension == "png" || extension == "jpg") {
var iDiv = document.createElement('div');
iDiv.id = 'images';
iDiv.className = 'item';
document.getElementById("image_div").appendChild(iDiv);
iDiv.appendChild(fragment);
var image = document.createElement("img");
image.className = "fancybox";
image.src = "images/" + filenames[i];
fragment.appendChild(image);
}
}
document.getElementById("images").appendChild(fragment);
}
</script>
then create a js file with the following:
然后使用以下内容创建一个js文件:
var g_FOLDER_CONTENTS = mlString(function() { /*!
1.png
2.png
3.png
*/});
回答by Pedro Reis
Using Chrome, searching for the images files in links (as proposed previously) didn't work as it is generating something like:
使用 Chrome,搜索链接中的图像文件(如先前所提议的)不起作用,因为它生成了类似的内容:
(...) i18nTemplate.process(document, loadTimeData);
</script>
<script>start("current directory...")</script>
<script>addRow("..","..",1,"170 B","10/2/15, 8:32:45 PM");</script>
<script>addRow("fotos-interessantes-11.jpg","fotos-interessantes-> 11.jpg",false,"","");</script>
Maybe the most reliable way is to do something like this:
也许最可靠的方法是做这样的事情:
var folder = "img/";
$.ajax({
url : folder,
success: function (data) {
var patt1 = /"([^"]*\.(jpe?g|png|gif))"/gi; // extract "*.jpeg" or "*.jpg" or "*.png" or "*.gif"
var result = data.match(patt1);
result = result.map(function(el) { return el.replace(/"/g, ""); }); // remove double quotes (") surrounding filename+extension // TODO: do this at regex!
var uniqueNames = []; // this array will help to remove duplicate images
$.each(result, function(i, el){
var el_url_encoded = encodeURIComponent(el); // avoid images with same name but converted to URL encoded
console.log("under analysis: " + el);
if($.inArray(el, uniqueNames) === -1 && $.inArray(el_url_encoded, uniqueNames) === -1){
console.log("adding " + el_url_encoded);
uniqueNames.push(el_url_encoded);
$("#slider").append( "<img src='" + el_url_encoded +"' alt=''>" ); // finaly add to HTML
} else{ console.log(el_url_encoded + " already in!"); }
});
},
error: function(xhr, textStatus, err) {
alert('Error: here we go...');
alert(textStatus);
alert(err);
alert("readyState: "+xhr.readyState+"\n xhrStatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>