javascript - I want to load images withen the folder and want to get all images in base64 in my js for future use -
i facing issue last image in image array due kind of filereader library function onloadend. how can base64 images in folder.
<input id="file-input" multiple webkitdirectory type="file" /> var input = document.getelementbyid('file-input'); var file_names = ""; var entries_length = 0; var entries_count = 0; var image = new array(); var obj = {}; var j = 0; input.onchange = function(e) { var files = e.target.files; // filelist entries_length = files.length; console.log(files); (var = 0, f; f = files[i]; ++i){ console.log("i:"+i); entries_count = entries_count + 1; //console.debug(files[i].webkitrelativepath); if(files[i].type=="image/jpeg") { var string = files[i].webkitrelativepath; var name = string.split("/")[3]; //this because image in 3rd dir in folder var reader = new filereader(); reader.onloadend = function() { obj.name = string.split("/")[3]; obj.image = reader.result; image[j] = obj; j = j+1; } reader.readasdataurl(files[i]); } } console.log(image); }
the issue caused asynchronous loading of files. iterate on array , set onloadend handler reader each time, start loading calling readasdataurl.
one problem time first image loads, possible for loop has completed, , i @ last index of array.
at point, obtaining path files[i].webkitrelativepath give last filename, , not 1 expecting.
check example readasdataurl on mdn see 1 possible solution - each load performed in separate function, preserves scope, along file.name. not put off construction using: [].foreach.call(files, readandpreview). way map on files, filelist , not regular array (so list not have foreach method of own).
so, should sufficient wrap loading logic in function takes file object parameter:
var images = []; function loadfile(f) { var reader = new filereader(); reader.onloadend = function () { images.push({ name : f.name, // use whatever naming magic prefer here image : reader.result }); }; reader.readasdataurl(f); } (var i=0; i<files.length; i++) { loadfile(files[i]); } each call of function 'remembers' file object called with, , prevents filename getting messed up. if interested, read on closures.
this has nice effect of isolating reader objects, because have sneaking suspicion that, although create new 'local' reader each iteration, javascript scoping rules weird , readers interfering each other (what happens if 1 reader loading, in same scope create new reader same variable name? not sure).
now, not know how long take images loaded, if want take action right after that, have perform check each time onloadend gets called. essence of asynchronous behavior.
as aside, should note pointless manually keep track of last index of images, j. should use images.push({ name: "bla", image: "base64..." }). keeping indices manually opens possibilities bugs.
Comments
Post a Comment