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

后端 未结 14 1975
情深已故
情深已故 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 11:06

    You can't do this automatically. Your JS can't see the files in the same directory as it.

    Easiest is probably to give a list of those image names to your JavaScript.

    Otherwise, you might be able to fetch a directory listing from the web server using JS and parse it to get the list of images.

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

    You can use the fs.readdir or fs.readdirSync methods to get the file names in the directory.

    The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.

    The second is synchronous, it will returns the file name array, but it will stop any further execution of your code until the read process ends.

    After that you simply have to iterate through the names and using append function, add them to their appropriate locations. To check out how it works see HTML DOM and JS reference

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

    This is the way to add more file extentions, in the example given by Roy M J in the top of this page.

    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.

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

    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:

    var g_FOLDER_CONTENTS = mlString(function() { /*! 
    1.png
    2.png
    3.png 
    */}); 
    
    0 讨论(0)
  • 2020-11-22 11:12

    Using Chrome, searching for the images files in links (as proposed previously) didn't work as it is generating something like:

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

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

    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

    Apache server has Option Indexes turned on by default - if you use another server like i.e. Express for Node you could use this NPM package for the above to work: 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:

    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')));
    
    0 讨论(0)
提交回复
热议问题