I'm using HTML5 and JavaScript for reading a text file, but now I need to read exactly 2 text files and do the same operations as done before but for the two files.
For the second file I've been trying with: var file2 = files[1]; and add a multiplein the html input, but how can I do it for the reader.onload = function (e) { part? I want to parse the two files in the same way, not only one.
Here is the code (simplified):
<!DOCTYPE html>
<html>
<head>
<title>Read and Parse Lynis Log</title>
<script>
function processFiles(files) {
var file = files[0];
var reader = new FileReader();
var textParsed = [];
reader.onload = function (e) {
var output = document.getElementById("fileOutput");
output.textContent = e.target.result;
var text = e.target.result;
var lines = text.split("\n");
for (var i= 0; i < lines.length; i++) {
textParsed[i] = lines[i];
}
var testsPerformed = null;
var suggestions = [];
var suggestion = null;
var auxSug = null;
for (var j = 0; j < lines.length; j++) {
if (textParsed[j].includes("tests_executed")){
testsPerformed = textParsed[j];
}
if (textParsed[j].includes("suggestion[]")) {
suggestion = textParsed[j];
suggestions.push(suggestion);
}
}
if (typeof(Storage) !== "undefined" && textParsed.length >= 1) {
//Store
localStorage.setItem('storedText', textParsed);
localStorage.setItem('tests', testsPerformed);
localStorage.setItem('suggestions', suggestions);
}
};
reader.readAsText(file);
}
</script>
</head>
<body>
<input id="fileInput" placeholder=":input" type="file" size="50" onchange="processFiles(this.files)">
<div id="fileOutput"></div>
</body>
</html>
You only need to initialize a FileReader for each file and start readAsText for every file. The function will be the same, I've modify the output so the content is not cleared with each file that is loaded.
<!DOCTYPE html>
<html>
<head>
<title>Read and Parse Lynis Log</title>
<script>
function processFiles(files) {
var file = files[0];
var textParsed = [];
function onReadAsText(e) {
var output = document.getElementById("fileOutput");
output.textContent = output.textContent + e.target.result;
var text = e.target.result;
var lines = text.split("\n");
for (var i= 0; i < lines.length; i++) {
textParsed[i] = lines[i];
}
var testsPerformed = null;
var suggestions = [];
var suggestion = null;
var auxSug = null;
for (var j = 0; j < lines.length; j++) {
if (textParsed[j].includes("tests_executed")){
testsPerformed = textParsed[j];
}
if (textParsed[j].includes("suggestion[]")) {
suggestion = textParsed[j];
suggestions.push(suggestion);
}
}
if (typeof(Storage) !== "undefined" && textParsed.length >= 1) {
//Store
localStorage.setItem('storedText', textParsed);
localStorage.setItem('tests', testsPerformed);
localStorage.setItem('suggestions', suggestions);
}
};
for (var i = 0; i < files.length; i++){
var reader = new FileReader();
reader.onload = onReadAsText;
reader.readAsText(files[i]);
}
}
</script>
</head>
<body>
<input id="fileInput" placeholder=":input" type="file" size="50" onchange="processFiles(this.files)" multiple>
<div id="fileOutput"></div>
</body>
</html>
Related
i currently have the ff code my goal is to remove the extra filreader loop? is it possible to maybe chain the readAsArrayBuffer and readAsDataURL or load them both?
var images = [];
var files = dt.files.length;
for (i = 0; i < files; i++) {
var reader = new FileReader();
reader.fileId = i;
reader.onload = function (){
images[this.fileId].is_valid = true / false; // checks mime type
}
reader.readAsArrayBuffer(dt.files[i]);
for (i = 0; i < files; i++) {
var reader = new FileReader();
reader.fileId = i;
reader.onload = function (){
//load image
if(image[i].is_valid){
// do this
}else {
// do this
}
}
reader.readAsDataURL(dt.files[i]);
I am trying to read excel file in Javascript with the plugin xlsx.js . I can read all cell values except the first value. Here is my code:
let numArr = [];
selectFile(event) {
let reader = new FileReader();
reader.onload = () => {
const data = reader.result;
const workbook = XLSX.read(data, {
type: 'binary'
});
workbook.SheetNames.forEach((sheetName) => {
// Here is your object
const XL_row_object = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);
// var json_object = JSON.stringify(XL_row_object);
for (let i = 0; i < XL_row_object.length; i++) {
// this.groupNumsArr.push(XL_row_object[i]['number']);
const theNum = Object.values(XL_row_object[i])[0].toString();
numArr.push(theNum);
}
});
};
reader.readAsBinaryString(event.target.files[0]); }
The api gives first row as key so You can try this
for (let i = 0; i < XL_row_object.length; i++) {
var theNum = '';
if(i == 0)
{
theNum = Object.keys(XL_row_object[i])[0].toString();
numArr.push(theNum);
}
// this.groupNumsArr.push(XL_row_object[i]['number']);
theNum = Object.values(XL_row_object[i])[0].toString();
numArr.push(theNum);
}
I have a code for displaying whole document in a HTML
<!DOCTYPE HTML>
<html>
<head>
<script>
let openFile = function(event) {
let input = event.target;
let reader = new FileReader();
reader.onload = function(){
let text = reader.result;
let node = document.getElementById('output');
node.innerText = text;
console.log(reader.result.substring(0, 200));
};
reader.readAsText(input.files[0]);
};
</script>
</head>
<body>
<input type='file' accept='text/plain' onchange='openFile(event)'><br>
<div id='output'>
</div>
</body>
</html>
I need to load a document then display only strings I need - names and url like:
Document example:
#NAME:Elis:
http://elis.com
#NAME:Emma:
http://emma.com
Display:
<a href=http://elis.com>Elis</a>
<a href=http://emma.com>Emma</a>
let openFile = function(event) {
let input = event.target;
let reader = new FileReader();
reader.onload = function() {
let text = reader.result;
let node = document.getElementById('output');
// node.innerText = text;
var resultText = "";
lines = reader.result.split(/\r\n|\r|\n/);
for (let i = 0; i < lines.length - 1; i += 2) {
var matches = lines[i].match(/\#NAME:([^:]+)/);
resultText += `${matches[1].trim()}\n`;
}
// innerText here only for demonstration purpose
// use innerHTML for working code instead
node.innerText = resultText;
// node.innerHTML = resultText
};
reader.readAsText(input.files[0]);
};
<input type='file' accept='text/plain' onchange='openFile(event)'><br>
<div id='output'>
var str = `#NAME:Elis:
http://elis.com
#NAME:Emma:
http://emma.com`;
const makeUpHrefs = str => {
let arr = str.split(/\n#/);
arr = arr.map(row => '' + row.match(/NAME:(.*?):/)[1] + '');
return arr;
};
So, makeUpHrefs(str) will return array of html's:
Elis
Emma
I have a question, how do I open all link from an array at the same time, not only one like it does now, I've tried something like this:
var urls = ["https://www.google.com", "https://www.facebook.com"];
let main = function() {
for (var i = 0; i < urls.length; i++) {
window.open(urls[i], '_blank');
}
};
main();
Can anybody show some examples? Thanks! :p
<html>
<head>
<script type='text/javascript'>
var urls = ["https://www.google.com", "https://www.facebook.com"];
function main() {
for (var i = 0; i < urls.length; i++) {
var el = document.querySelector('#hidden') ;
//window.open(urls[i], '_blank');
var a = document.createElement('a');
a.href = urls[i];
a.target = '_blank';
el.appendChild(a);
a.click();
}
}
window.addEventListener('load', function () { main();}, !1);
</script>
</head>
<body>
<div id='hidden'></div>
</body>
</html>
Here i did multiple file images with base64 conversion , everything working fine , for my requirement user select the multiple images and click the submit button means i have to take the values(file) and converted to base64 encoded string,here when select image that time it will working fine but going submit the button i am getting undefined how to solve this error
$(document).ready(function(){
$("input[name=property_images]").change(function() {
var imgBase64Arr = [];
var files = this.files;
for (var i = 0; i < files.length; i++) {
(function(i){
var FR = new FileReader();
FR.onload = function(e) {
var res = e.target.result ;
var arr1 = res.split(",");
var property_image = arr1[1] ;
imgBase64Arr.push( property_image);//adding base64 value to array
if(i === files.length -1)//after all files are porcessed
myFunction(imgBase64Arr)
};
FR.readAsDataURL(files[i]);
})(i);
}
});
});
function myFunction(imgBase64Arr){
console.log(imgBase64Arr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="file" name="property_images" multiple="multiple" />
<input type="button" value="submit" onclick="myFunction()">
When press submit button you call "myFunction" without passing anything..
$(document).ready(function(){
var imgBase64Arr = [];
$("input[name=uploadBtn]").click(function(){
console.log(imgBase64Arr);
});
$("input[name=property_images]").change(function() {
imgBase64Arr = [];
var files = this.files;
for (var i = 0; i < files.length; i++) {
(function(i){
var FR = new FileReader();
FR.onload = function(e) {
var res = e.target.result ;
var arr1 = res.split(",");
var property_image = arr1[1] ;
imgBase64Arr.push( property_image);//adding base64 value to array
if(i === files.length -1)//after all files are porcessed
myFunction(imgBase64Arr)
};
FR.readAsDataURL(files[i]);
})(i);
}
});
});
function myFunction(imgBase64Arr){
console.log(imgBase64Arr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="file" name="property_images" multiple="multiple" />
<input type="button" name="uploadBtn" value="submit">
Your imgBase64Arr variable is not globally defined. Please defined it globally.