HTML JavaScript print from file onto page - javascript

I have a problem with a little site (it's intended to work as a local site) I try to create.
I want it to print text from local txt file onto the page. I want it to display it like this one,
<script type="text/javascript">
var arr = ['Heading 1','Para1','Heading 2','Para2','Heading 3','Para3'];
var result = arr.map((val, i) => i%2===0 ? `<h2>${val}</h2>` : `<p>${val}</p>`).join('');
document.getElementById('test').innerHTML = result ;
</script>
but I want it to do it from a file, like this one
<script>
var fileInput = document.getElementById('inputfile');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('output').innerText = reader.result;
};
reader.readAsText(file);
});
</script>
I tried to merge them together like this
<script>
var fileInput = document.getElementById('inputfile');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('output').innerHTML = reader.result.split("\n").map((val, i) => i%2===0 ? <h2>${val}</h2> : <p>${val}</p>).join('');
};
reader.readAsText(file[0]);
});
</script>
But something is still not working right (after choosing the file to read, it does nothing) and I am not sure what am I doing wrong. I am green in javascript, so I would appreciate any help in that matter.

Actually, now that I read that again - the only issue with your example is you were using file[0] instead of file
<input type="file" id="inputfile" />
<p id="output"></p>
<script>
var fileInput = document.getElementById('inputfile');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('output').innerHTML = reader.result.split("\n").map((val, i) => i%2===0 ? `<h2>${val}</h2>` : `<p>${val}</p>`).join('');
};
reader.readAsText(file); // HERE!
});
</script>

Related

Parsing through excel file and storing variables

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>
<script>
var ExcelToJSON = function() {
this.parseExcel = function(file) {
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
workbook.SheetNames.forEach(function(sheetName) {
// Here is your object
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
var json_object = JSON.stringify(XL_row_object);
console.log(JSON.parse(json_object));
jQuery('#xlx_json').val(json_object);
})
};
reader.onerror = function(ex) {
console.log(ex);
};
reader.readAsBinaryString(file);
};
};
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var xl2json = new ExcelToJSON();
xl2json.parseExcel(files[0]);
}
</script>
<form enctype="multipart/form-data">
<input id="upload" type=file name="files[]">
</form>
<textarea class="form-control" rows=35 cols=120 id="xlx_json"></textarea>
<script>
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
</script>
Hello, from the above snippet of code, I am trying to read in the variables from each parsed row in the excel file (the code takes an excel file and prints all the data by row), the best way to describe what I want would probably be something like this in c++(only way I know how to communicate).
void read(string fileName) {
// assume int a,b,c are already declared
// assuming first row of parsed data is vector
for (int i = 0; i < rows.size(); i++) {
a = vector[i][0];
b = vector[i][1];
c = vector[i][2];
// code for thing I am doing here(doesnt matter)
}
}
Is there something like this in javascript or a different method potentially?
I believe that I figured out the answer to my question.
// to access a specific element, I need to do something like this
var obj = JSON.parse(json_object);
a = obj[0]["value"];

java script: How can I read html file and load its content to a div

I'm trying to read a html file from client computer and load its body content to a div. However, I'm not sure about the correct way to do that. I tried apply these to an uploaded file:
$('#theFile').on("change", function () {
var file = (this).files[0];
var reader = new FileReader();
reader.onload = function (e) {
str = e.target.result;
slides = new Array(1);
var pattern = new RegExp(/<body[^>]*>((.|[\n\r])*)<\/body>/im);
var res = str.match(pattern).join();
console.log(res);
$('#slide').html(res);
slides[0] = res;
};
reader.readAsText(file);
});
The res is an array with 3 elements so I joined them together. Is there better solutions which don't engage with regular expressions?
Add a file-input element to the HTML page:
<input type="file" id="file" onchange="readTxT()"/>
And select sample.txt manually:
function readTxT(){
var reader = new FileReader();
var files=document.getElementById('file').files;
var f = files[0];
reader.onload = function(e) {
var text = reader.result;
$(".diagram").text(text);
}
reader.readAsText(f);
}

How to determine if PDF is encrypted javascript client side

Need to determine if if pdf uploaded by user is password protected without using external libs.
So far got this POC.
Any one know cases when this might not work?
<input type='file' onchange='openFile(event)'><br>
<script>
var openFile = function (event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function (event) {
console.clear();
var contents = event.target.result;
if (contents.indexOf('/Encrypt') !== -1) {
console.log("Is encrypted");
} else {
console.log("Not encrypted");
}
console.log("File contents: " + contents);
};
reader.onerror = function (event) {
console.error("File could not be read! Code " +event.target.error.code);
};
reader.readAsText(input.files[0]);
};
</script>
You can use the below code to find whether the PDF is encrypted or not
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function () {
var files = new Blob([reader.result], {type: 'application/pdf'});
files.text().then(x=> {
console.log("isEncrypted", x.includes("Encrypt"))
console.log("isEncrypted", x.substring(x.lastIndexOf("<<"), x.lastIndexOf(">>")).includes("/Encrypt"));
console.log(file.name);
});

"change" event lags one step behind javascript

I am trying to make a very simple webpage that takes an input file and displays the contents in the console. When I try to use it, it sort of works, but is always one step behind. For example,
1) Upload "1.txt" -> Console prints ""
2) Upload "2.txt" -> Console prints contents of "1.txt"
3) Upload "3.txt" -> Console prints contents of "2.txt"
...
function readData(){
var fileholder = document.querySelector('#knotFiles');
var content = 'Empty';
var reader = new FileReader();
reader.onload = function(event){
content = event.target.result;
}
fileholder.addEventListener("input", function(event) {
var files = fileholder.files;
reader.readAsText(files[0]);
console.log(content);
}, false);
return content;
};
readData();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="" />
<title></title>
</head>
<body>
<div id="container">
<input type="file" id="knotFiles" multiple>
</div>
<script src="knot.js">
</script>
</body>
</html>
I am new to javascript and web development in general, so I apologize if this is a simple question. Thank you!
render.onload is a async function In sort content = event.target.result; will execute at the end so put console.log(content); inside render.onload for latest changes in content data
function readData(){
var fileholder = document.querySelector('#knotFiles');
var content = 'Empty';
var reader = new FileReader();
reader.onload = function(event){
content = event.target.result;
console.log(content);
}
fileholder.addEventListener("input", function(event) {
var files = fileholder.files;
reader.readAsText(files[0]);
}, false);
return content;
};
readData();
The FileReader() loads asynchronously - you are outputting the previous result because the variable content has not been updated yet before the event listener callback fires. Rewrite like this:
var fileholder = document.querySelector('#knotFiles');
fileholder.addEventListener("input", function(event) {
readData();
}, false);
function readData(){
var content = '';
var files = fileholder.files;
var reader = new FileReader();
reader.readAsText(files[0], "UTF-8"); // assumed this encoding
reader.onload = function(event){
content = event.target.result;
console.log(content);
return content;
};
}

How to read HTML file contents in javascript

I am sending data via ajax to post in mysql. In this context how to inlude image file contents ?
If i use like :
var formData = document.getElementById("img_file");
alert(formData.files[0]);
, i get error . Note : img_file is the id of the file dom.
Any idea about this ?
You can use javascript FileReader for this purpose. Here is a sample code demonstration.
<html>
<body>
<input type="file" id="fileinput" />
<div id="ReadResult"></div>
<script type="text/javascript">
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function (e) {
var contents = e.target.result;
document.getElementById("ReadResult").innerHTML = contents;
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</body>
</html>
Find more details here.
i think it may help you.
$('#image').change(function () {
$("#add").attr("disabled", true);
var img = this.files[0];
var reader = new FileReader;
reader.readAsDataURL(img);
reader.onload = function (e) {
var file = new Image;
file.src = e.target.result;
file.onload = function () {
$("#height").text(file.height);
$("#width").text(file.width);
$("#imageprev").attr("src", file.src);
$("#upld").removeAttr("disabled");
}
}
});

Categories