Reputation: 1
I am writing a simple website which loads multiple images in a local directory using a txt file containing all of these the images' names.
The flow is that the website reads the txt file for images' names (i.e. 1.jpg) then loads the images with the corresponding names to the website.
I am currently stuck at this. Any suggestion is welcome :)
UPDATE 1
My apologies. I have successfully read the input file line by line. Although, I have not figured out how to add each line into a array for loading them later.
Code in JavaScript
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// By lines
var lines = this.result.split('\n');
arr
for(var line = 0; line < lines.length; line++){
console.log(lines[line]);
}
};
reader.readAsText(file);
};
Code in HTML
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<input type="file" name="file" id="file">
<script type="text/javascript" src= "Functions.js"></script>
</body>
</html>
UPDATE 2
I think I have added the names into an array (ImageNameList), still I am having trouble with displaying all the images. Here is what I have so far:
JavaScript
document.getElementById('file').onchange = function(){
var file = this.files[0];
var ImageNameList = [];
var reader = new FileReader();
reader.onload = function(progressEvent){
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
console.log(lines[line]);
ImageNameList.push(lines[line]);
document.getElementById("test").innerHTML = ImageNameList;
}
};
reader.readAsText(file);
};
function displayAllImages() {
var i = 0,
len = ImageNameList.length;
for (; i < ImageNameList.length; i++) {
var img = new Image();
img.url = ImageNameList[i];
img.style.width = '160px';
img.style.height = '120px';
document.getElementById('images').appendChild(img);
}
};
HTML
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<input type="file" name="file" id="file">
<div id="test"></div>
<div id="container">
<div class="ImageNameList">
<ul id="images"></ul>
</div>
</div>
<script type="text/javascript" src= "Functions.js"></script>
</body>
</html>
Upvotes: 0
Views: 1276
Reputation: 2799
I suggest you change from a txt file to a json file so that the client can parse it.
{
"filenames": ["1.jpg", "2.jpg"]
}
Then you can load the json file with a xhr request and parse the response body with JSON.parse.
Hope this helps. I can give a more complete example when not on the phone if needed.
Upvotes: 1