Reading in a text file to display in HTML - javascript

I am just working on a web site for fun and I was wondering if you could use JavaScript to read in a local text file and then display it HTML. So for example if I had a text file saved with my project then could I write a function in JavaScript that reads the entire file and then just displays all that text within on the web page?
I've looked around and tried to find something that will do this, but I don't think I fully understand. I have:
function readFile(fileName){
var fileRead = new ActiveXObject('Scripting.FileSystemObject');
text = fileRead.OpenTextFile(fileName, 1, false, 0);
while(!text.AtEndOfSteam){
text += text.ReadLine();
}
text.Close();
}
I don't know if this is will work or do what I want to do. So my question is, how do I use JavaScript to read in a text file, then display the contents of that text file on a webpage in HTML?

You have to use the File API.
var input = document.getElementById("myFile");
var output = document.getElementById("output");
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', function (e) {
output.textContent = e.target.result;
});
reader.readAsBinaryString(myFile);
}
});
<input type="file" id="myFile">
<div id="output"></div>
EDIT
After reading your comment, i think this is what you want.
var output = document.getElementById("output");
$("a").on("click", function (e) {
e.preventDefault();
$.ajax(this.href).done(function(data) {
output.textContent = data;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
Link to file

<html>
<head>
<title>reading file</title>
</head>
<body>
<input type="file" id="myFile">
<hr>
<!--<div style="width: 300px;height: 0px" id="output"></div>-->
<textarea style="width:500px;height: 400px" id="output"></textarea>
<script>
var input = document.getElementById("myFile");
var output = document.getElementById("output");
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', function (e) {
output.textContent = e.target.result;
});
reader.readAsBinaryString(myFile);
}
});
</script>
</body>
</html>

Related

How can I output multiple lines of a text file in HTML using JS?

This is only the section of the code that I can't solve. The idea is that I open the text file, which I can do, and then I output each line in the div with the id cont. when I open the text file nothing gets output. I don't know why.
<head>
<title>Read Text File</title>
</head>
<body>
<input type="file" name="file" id="file" />
<br>
<div id ="cont"></div>
<script>
document.getElementById('file').onchange = function()
{
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent)
{
var fileContentArray = this.result.split(/\r\n|\n/);
for(var line = 0; line < lines.length-1; line++)
{
document.getElementById("cont").innerHTML = lines[line];
}
}
reader.readAsText(file);
}
</script>
</body>
</html>

with just javascript can you combine file input upload and speechSynthesis -no jquery please

So here is a basic code idea of what I am trying to do. I would like to press a button select a text file and have it read it to me. Basically just reading short notes and stuff that were entered in txt. Still new playing with javascript. this seems easy enough but Google came back empty? can this even be done?
<html>
<body>
<input type="file" id="myFile">
<button onclick="speak(myFile)">speak dang it</button>
<script>
function speak(text) {
var msg = new SpeechSynthesisUtterance();
var voices = speechSynthesis.getVoices();
msg.voice = voices[2];
msg.voiceURI = 'native';
msg.volume = 1;
msg.rate = 1;
msg.pitch = 1;
msg.text = text;
msg.lang = 'en-US';
speechSynthesis.speak(msg);
}
</script>
</body>
</html>
You have access to the file via window.FileReader or window.Blob.
Have a read here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
Update
Example:
<html>
<body>
<input type="file" id="myFile">
<button id="speak">speak dang it</button>
<script>
if( window.FileReader && window.speechSynthesis ) {
const fileInput = document.getElementById("myFile");
fileInput.addEventListener("change", event => {
const Reader = new FileReader();
Reader.readAsText( fileInput.files[ 0 ] );
Reader.onload = event => {
const contents = Reader.result;
const utterThis = new SpeechSynthesisUtterance( contents );
speechSynthesis.speak( utterThis );
}
});
}
</script>
</body>
</html>
You should make sure you sanitise the input and check file type and all that but this is the smallest example I can think of...

Unable to read data from multiple files using HTML FileReader

<input type="file" id="input" multiple onchange="handleFiles(event.target)">
<script language="javascript" type="text/javascript">
<!--
function handleFiles(input)
{
for (i = 0; i < input.files.length; i++)
{
var reader = new FileReader();
reader.onload = function()
{
alert(reader.result)
};
reader.readAsText(input.files[i]);
}
}
//-->
</script>
I am trying to display the contents of some files that I upload. It works fine if I select a single file, but if I select multiple files, only the content of one file is displayed, rest all are blank. What am I doing wrong?
You just need to amend it slighty to do the following:
<input type="file" id="input" multiple onchange="handleFiles(event.target)">
<script language="javascript" type="text/javascript">
function handleFiles(input)
{
for (var i = 0; i < input.files.length; i++) { //for multiple files
(function(file) {
var name = file.name;
var reader = new FileReader();
reader.onload = function(e) {
// get file content
var text = e.target.result;
alert(text)
}
reader.readAsText(file, "UTF-8");
})(input.files[i]);
}
}
</script>
Reference: https://stackoverflow.com/a/9815648/3088780
I think jquery help you easily
HTML:
<script src="jquery-2.2.0.min.js"></script>
<input type="file" multiple="multiple" />
<ul id="output">
</ul>
Jquery:
$('input:file[multiple]').change(
function(e){
console.log(e.currentTarget.files);
var numFiles = e.currentTarget.files.length;
for (i=0;i<numFiles;i++){
fileSize = parseInt(e.currentTarget.files[i].size, 10)/1024;
filesize = Math.round(fileSize);
$('<li />').text(e.currentTarget.files[i].name).appendTo($('#output'));
$('<span />').addClass('filesize').text('(' + filesize + 'kb)').appendTo($('#output li:last'));
}
});
reference from : https://stackoverflow.com/a/7719334/5566169

How do you read a local file on your PC and update it constantly in javascript?

So, I've made a java program that runs through a list of IPs, pings them, and updates a file on the devices status. I want to know how to open the file into a webpage and update it, so a user can open the webpage and just see a list of data from the file, they don't have to select the file or refresh the page.
Is this feasible to do with javascript/html?
This is the code I'm working with so far:
<html>
<head>
<title>Import Data</title>
<script>
var openFile = function() {
var input = event.target;
var reader = new FileReader();
reader.onload = function() {
var text = reader.result;
var node = document.getElementById('output');
node.innerText = text;
console.log(reader.result.substring(0,200));
};
reader.readAsText(input.files[0]);
setTimeout(openFile(),1000);
};
</script>
</head>
<body>
<input type='file' accept='text/plain' onchange='openFile()'><br>
<div id='output'>
</body>
</html>
But I can't seem to hunt down where to hardcode the path to the file in. When I use this manual selection method, it'll update once, whether the file increases in elements or decreases.
EDIT:
I've narrowed it down to where the file needs to be uploaded:
<html>
<head>
<title></title>
<script>
function uploadFile() {
var reader = new FileReader();
reader.onload = function(event) {
var contents = event.target.result;
console.log("File contents: " + contents);
};
reader.onerror = function(event) {
console.error("File could not be read! Code: " + event.target.error.code);
};
var fileInputElement = document.getElementById("FileName");
reader.readAsText(fileInputElement.files[0]);
console.log(fileInputElement.files[0]);
}
</script>
</head>
<body>
<input type='file' accept='text/plain' value='RESULTS.txt' id='FileName' onchange='uploadFile()' style="display:none;">
</body>
</html>
If I try to type just a file path in a string, it complains it's not type 'blob'. When I do this, it requires the user to enter a file name, but obviously it can't be seen. How can I make that 'file' variable a static variable so it always opens a that file without prompting the user?
Doing some more research, it's security reasons as to why you can't access a file from the local computer.
So, in lieu of all that, I made some code that will constantly load the selected file so you can see whenever it changes:
<html>
<head>
<title>Import Data</title>
<script>
var input;
var openFile = function() {
var reader = new FileReader(event);
reader.onload = function() {
var text = reader.result;
var node = document.getElementById('output');
node.innerText = text;
console.log(reader.result.substring(0,200));
};
reader.readAsText(input.files[0]);
setTimeout(openFile,1000);
};
</script>
</head>
<body>
<input type='file' accept='text/plain' onchange='input = event.target; openFile(event);'><br>
<div id='output'>
</body>
</html>

HTML not rendering the img after I change src on the run time

I have the following code -
<html>
<head>
<script>
function myFunction()
{
var x = document.getElementById("myFile");
alert(x.value);
document.getElementById("picture").src=x.value;
}
</script>
</head>
<body>
<input type="file" id="myFile"><br>
<button onclick="myFunction()">Render this</button>
<img id="picture" src="C:\Users\Shin\Desktop\410.svg">
</body>
</html>
Initailly its showing the image, after I select another file and click the button, it shows me the path in the alert box perfectly but, it doesnt render the new pic and its showing a red cross at the place what you see in image when the src is incorrect. I used chrome browser.
try this...
<html>
<head>
<script>
function myFunction()
{
var input = document.getElementById("myFile");
var fReader = new FileReader();
fReader.readAsDataURL(input.files[0]);
fReader.onloadend = function(event){
var img = document.getElementById("picture");
img.src = event.target.result;
}
}
</script>
</head>
<body>
<input type="file" id="myFile"><br>
<button onclick="myFunction()">Render this</button>
<img id="picture" src="C:\Users\rajpc\Pictures\1390.jpg">
</body>
</html>
this would definitely work....
Change your img src as desired..
I hope this should help you....
you'll need URL.createObjectURL for that:
url=URL.createObjectURL(x[0]);
To read a local file you would need to use the FileReader Api.
function myFunction() {
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById("picture").src = reader.result;
};
reader.readAsDataURL(document.getElementById("myFile").files[0]);
};

Categories

Resources