简体   繁体   中英

Loading images from file with Javascript

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.

Prerequisite: Adjust chromium / chrome launcher to add required flag , eg; 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")
})

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.

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 /> 

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM