问题
I want to display all images from a directory dynamically with the help of javascript. How can I do this?
回答1:
I don't believe that it is possible, but if you make an AJAX request to an ASP.NET or PHP (or similar) page, they can list the files in the folder and return it for the Javascript to show.
The cross-domain policy obviously applies.
If you are using PHP, you should use recursion on directories to get the full file structure. PHP has a Scan Directory Function that you can use.
Basic code example:
function listdir($folder) {
if (!is_dir($folder)) {
return array(); //empty if not a folder
}
$return = scandir($folder);
$subfolders = array();
array_shift($return); //first two values are always .. & .
array_shift($return);
foreach ($return as $key => $value) {
if (is_dir($value)) {
unset($return[$key]);
$subfolders[$value] = listdir($value); //recursively analyse the subdirectory
}
}
return array_merge(array_values($return), $subfolders);
}
Note: This hasn't been tested, please tell me if it doesn't work.
回答2:
Basic PHP example:
<?php
foreach(glob("/path/to/images/{*.gif,*.jpg,*.png,*.jpeg,*.bmp}", GLOB_BRACE) as $image){
echo '<img src="'.$image.'">';
}
回答3:
Doing this using purely javascript is not possible unless the directory has indexes or you know the file names beforehand. Still an alternative using php is as follows:
Send an ajax request to a php file with data as directory name
The PHP file then access the directory contents using
opendir
,readdir
,scandir
etc commands. See this SO question or this link for more details on reading a directory by php readdir/scandir commands or this(by glob)The PHP file returns the file names (here image names) as a json object.
On the client side the ajax response comes as the json object.
Done! You have all the images in that folder.
来源:https://stackoverflow.com/questions/10943405/how-to-display-all-images-of-a-directory-in-javascript