0

I'm trying to load all the images inside a folder(I have more than 20K), to show them to users(just trying to build a page with images everywhere), on page load, using a JS inside my HTML. But I couldn't manage to load images. There is no error on web console also.

What's wrong with this code?

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

    </head>

    <body>
        <script>               
        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 +"'>" );
                        } 
                    });
                }
            });
        </script>
    </body>
</html>

Also, other solutions without JS to achieve the same thing appreciated as well.

Thanks in advance.

18
  • Perhaps your path is wrong. Try /images instead of images/. Commented Feb 21, 2016 at 1:30
  • What is in data? In most webservers, requesting a directory won't give you a JSON-encoded list of its contents Commented Feb 21, 2016 at 1:31
  • @JohnDoe I used this answer for JS: stackoverflow.com/a/32940532/1079908. I'm not sure what that data is Commented Feb 21, 2016 at 1:33
  • @Saibot requesting a directory on your webserver might get a different response than on the OP of that question did. Commented Feb 21, 2016 at 1:36
  • @JohnDoe Maybe, I would appreciate another solution, if you have. Commented Feb 21, 2016 at 2:06

4 Answers 4

1

Prerequisite: Adjust chromium / chrome launcher to add required flag , e.g.; chromium-browser --allow-file-access-from-files or google-chromne --allow-file-access-from-files ; see How do I make the Google Chrome flag "--allow-file-access-from-files" permanent?

html, having number of img elements equal to image files in folder

<!-- note , `src` attribute not included -->
<img class="image" style="opacity:0.0" alt="1">
<img class="image" style="opacity:0.0" alt="1a">
<img class="image" style="opacity:0.0" alt="1b">
<img class="image" style="opacity:0.0" alt="1c">

You should then be able to use approach described at Preloading images in HTML to iterate an array of image file names to load multiple images in succession.


Using XMLHttpRequest() with responseType set to Blob , URL.createObjectURL , new Promise() constructor , Promise.all()

var arr = ["file:///home/user/path/to/image/file-1"
          , "file:///home/user/path/to/image/file-2"];

function loadImages(src) {
  return new Promise(function(resolve, reject) {
    var request = new XMLHttpRequest();
    request.onload = function() {
      $("<img/>", {
        src: URL.createObjectURL(this.response)
      }).on("error", reject)
      .appendTo("body");
      resolve(src + " loaded")
    }
    request.onerror = reject;
    request.open("GET", src);
    request.responseType = "blob";
    request.send(); 
  }) 
}  

Promise.all(arr.map(function(src) {
  return loadImages(src)
}))
.then(function(data) {
   console.log(data)
}, function(err) {
   console.log("error", err)
})

See also jquery-ajax-native which allows Blob or ArrayBuffer to be returned from jQuery.ajax()

$.ajax({
    dataType: 'native',
    url: "file:///home/user/path/to/image/file",
    xhrFields: {
      responseType: "blob"
    }
})
.then(function(data) {
  $("<img/>").attr("src", URL.createObjectURL(data))
  .appendTo("body")
})
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for answer. But as far as I understand, I need to have a var arr array size equals to image number, also equal number of <img ... But I have more than 20K images, and this is not practical. Plus, I'm running the html on my computer for now, but I'm planning to host it as a website, and if users need to tweak their browsers to see my website, that's not practical again too.
@Saibot The initial premise of original Question was that you were performing these actions locally ? Not on a website that was live on web. That is why included portion about allowing local access to files using a flag at chromium , chrome to use $.ajax() locally. The img elements can be dynamically created instead of written in the html document. "I can write a script to name all the images like 1, 2, 3 etc. that's no problem." , "But I have more than 20K images, and this is not practical." Whether 20 images or 20k images should not affect process.
Maybe I don't get what you explain, I have to study these things for a while. Thanks anyway, upvoting your answer.
1

Try using input type="file" with multiple and webkitdirectory , attributes set, accepts attribute set to "image/*" , .change(), for loop , IIFE to create a closure within for loop, URL.createObjectURL()

$(":file").change(function(event) {
  var files = this.files;
  for (var i = 0; i < files.length; i++) {
    (function(n) {
      var img = new Image;
      img.onload = function() {
        $("body").append(this)
      }
      img.src = window.URL.createObjectURL(files[n])
    }(i))
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="file" accepts="image/*" multiple webkitdirectory />

4 Comments

Nice answer, thanks. But what I want is to load all images from a folder when the page loads, to show them to users. Your example is to post images from folder. I think you misunderstood me.
@Saibot Do all images have similar file name ? Even if they do not, you could compile a list of file names and use $.ajax() to load each file, in succession, into document . At terminal you could use $ cd ~/path/to/folder , $ ls to list all files in folder /path/to/folder . Once you have the list of files, you can create an array of file names for use with $.ajax()
I can write a script to name all the images like 1, 2, 3 etc. that's no problem. Can you show an example, assuming I have a filename list?
Yes, will post another solution
1

In the code listed above, theres no way you are getting anything in the data that is being returned in ajax as url:"images/" is a folder. You would need to set the url to something that supplies the list of paths of the respective files like a json response:

{1:"images/abc.jpg",2:"images/abc.jpg"}

OR

{imagelinks:["images/abc.jpg","images/abc.jpg"]}

Then you can supply these text path to the image sources on page.

3 Comments

Problem is, it is too impractical if you have 20k images.
Wait wait, you mean I have to prepare a directory list, and use that list in the function?
Yes a directory list or something on these lines on server side. You can also refer: stackoverflow.com/questions/6994212/…
0

The inclusion of "folder" when you append creates a redundancy in the file paths. Remove that and it works great:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
    <script>               
    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='" + val +"'>" );
                    } 
                });
            }
        });
    </script>
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.