How to load all the images from one of my folder into my web page, using Jquery/Javascript

后端 未结 14 1952
情深已故
情深已故 2020-11-22 10:18

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.

<
相关标签:
14条回答
  • 2020-11-22 10:56

    In jQuery you can use Ajax to call a server-side script. The server-side script will find all the files in the folder and return them to your html file where you will need to process the returned information.

    0 讨论(0)
  • 2020-11-22 10:58

    Here is one way to do it. Involves doing a little PHP as well.

    The PHP part:

    $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:

    $.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.

    Had some help on the php part from 1

    0 讨论(0)
  • 2020-11-22 11:00

    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).

    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.

    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.

    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.

    var filenames = g_FOLDER_CONTENTS.match(/\S+/g);
    

    Here's an example of it all put together: image_loader.zip

    In the example, run.bat generates the Javascript file and opens index.html, so you needn't open index.html yourself.

    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.

    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.

    0 讨论(0)
  • 2020-11-22 11:00

    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.

    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
        });
    }
    
    0 讨论(0)
  • 2020-11-22 11:01

    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().

    P.s : The above source code is not tested.

    0 讨论(0)
  • 2020-11-22 11:02

    This is the code that works for me, what I want is to list the images directly on my page so that you just have to put the directory where you can find the images for example -> dir = "images /" I do a substring var pathName = filename.substring (filename.lastIndexOf ('/') + 1); with which I make sure to just bring the name of the files listed and at the end I link my URL to publish it in the body

    $ ("body"). append ($ ("<img src =" + dir + pathName + "> </ img>"));
    
    <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <title></title>
        <script src="jquery-1.6.3.min.js"></script>
            <script>
    
    
            var dir = "imagenes/";
            var fileextension = ".jpg";
            $.ajax({
                //This will retrieve the contents of the folder if the folder is configured as 'browsable'
                url: dir,
                success: function (data) {
                    //Lsit all png file names in the page
                    $(data).find("a:contains(" + fileextension + ")").each(function () {
                        var filename = this.href.replace(window.location.pathname, "").replace("http://", "");
                var pathName = filename.substring(filename.lastIndexOf('/') + 1);               
                        $("body").append($("<img src=" + dir + pathName + "></img>"));
                console.log(dir+pathName);
                    });
                }
            });
    
    
    
            </script>
    
      </head>
      <body>
    <img src="1_1.jpg">
      </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题