Loading and Reading text file onto HTML/JavaScript - javascript

I am trying to read and load a locally stored text file (it's saved on the user's computer, but may be moved to a local directory) into a variable or array so that I can generate a table with it in HTML.
I have found a way to have the user select and upload the file, but the code displays the text on the browser. I want it stored so I can manipulate the data so that I can put it in the correct row and cell. I know how to create a table, format it, format and splice text and things similar to that.
The code, which I found here but forgot which specific ask it was, goes as follows
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
For reference, here's a sample of the text file and here's what I want.
I am still relatively new to HTML and Javascript, but eager to learn. Anything will be appreciated.

You already have some parts working:
You have found a way to have the user select and upload the file
You know how to create a table, format it, format and splice text and things
Now we need to connect these things. Unfortunately, now all the script does is display the text on the browser when the user loads a text file. This is the part of the code responsible for that:
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
It displays it inside the <pre id="fileDisplayArea"><pre> area of your html. You want to store it inside a variable, so you can start to create a table, format it, format and splice text and things (the part 2 you already know):
reader.onload = function(e) {
myTextToFormat = reader.result;
// start formatting and make it into a table...
}

Related

in js, why is my filereader unable to track my inputfile when I edited it

Maybe naive question but I'm wondering this:
I have an html input allowing me to find a local file on my computer. <input type="file" id="importFile">
From this input, i create a FileReader in js to display the text file content on my page
var search_file = document.getElementById("search_file")
search_file.addEventListener('change', function(){
var reader = new FileReader();
var tmp = [];
reader.readAsText(file_to_survey);
reader.onload = function(e) {
var contents = e.target.result;
//function to edit html thanks to content//
}, false);
This part is actually working well BUT if I edit or replace the file I targeted (with exact same file name), I'm not able to display the file without to search it again with the html input mentionned above.
Is there a way to keep trace of my file even after edition?
Many thanks for your help. I dug quiet a lot to solve my problem but maybe I'm thinking the wrong way. Any clue would be nice.
Because that's how the input type=file element works, and to my best knowledge there is no way for you to force the browser to automatically re-read a file from the user's hard drive without their express consent.
You can put the change handler of the file input in a separate function, and call that function when needed.
function loadFile () {
var reader = new FileReader();
reader.addEventListener('load', function () {
file = reader.result;
// Handle the changes here
console.log(file);
});
reader.readAsText(fileField.files[0]);
}
const fileField = document.getElementById('load'),
reloadBut = document.getElementById('reload');
let file;
reloadBut.addEventListener('click', loadFile);
fileField.addEventListener('change', loadFile);
<input type="file" id="load">
<button id="reload">Load</button>
A separate button is used to reload the file in this snippet, but you can call loadFile where ever you need, ex. in an interval or from some event handler knowing the file was changed etc.
Note: This works in Chrome only, other browsers seem to lose the reference to the file browsed into file input when the file is changed. Also, the file must be properly closed after saving, before reloading.

Using only pure javascript how to get file name, format and content of a browsed file

I need to get the name, format and content of a browsed file only, multiple files not required. Even I cant use any HTML5 API/jQuery. Could you please guide me, using only pure JavaScript how do I solve this.
Here is the fiddle:
[https://jsfiddle.net/summtz8m/][1]
After getting all I need to click ImportASN1 button to POST data in REST service.
Here is my HTML
<button class="ebBtn" id="importButt" name="importButt"><span>Import ASN1</span></button><input type="file" id="myfile" name="myfile"><p id="contents"></p>
Here is my JS
var file = document.getElemtById("myfile").files[0];
console.log(file);
if (file) {
// create reader
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(e) {
// browser completed reading file - display it
console.log(e.target.result);
};
}
Your current code runs on page load. But at that time the file input is not filled out yet! Instead, listen to the click event on the button, or the change event on the file input.
In addition, there is a typo: document.getElemtById should be document.getElementById. Use the developer console in your browser (F12 → Console in many browsers) to find these errors.
The file name will then be present in the file.name property.
<script>
document.getElementById("myfile").addEventListener('change', function(ev) {
var file = ev.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(e) {
console.log(file.name, e.target.result);
};
});
</script>

How to read local files using HTML 5 FileReader? [duplicate]

This question already has answers here:
Javascript read file without using input
(3 answers)
Closed 6 years ago.
Objective
I am making an application, and I need to read a local file using JavaScript and HTML 5, without any <input> tags or user interaction whatsoever.
What I tried
On my research, I found two tutorials that are heavily cited in SO:
https://www.html5rocks.com/en/tutorials/file/dndfiles/
http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api
However, there is a problem. Both of this tutorials require user interaction via the input tag, which is a life killer since I want to read the contents of the file automatically into a string.
Code
So far I managed to get the following code:
let readFile = function(path) {
let reader = new FileReader();
reader.onload = function(e) {
var text = reader.result;
console.log(text);
};
// Read in the image file as a data URL.
reader.readAsText(MissingFileHandle);
};
But as you can see, I am missing an important step, I am missing MissingFileHandle. My idea would be to pass a path to this method, and so the method would read the file locally as text and print it into the console, but I am unable to achieve this.
Question
Given a relative path, how can I read the contents of a file using HTML 5 without using <input> tags?
The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.
Is it possible to load a file with JS/HTML5 FileReader on non served page?
How to open a local disk file with Javascript?
How to set a value to a file input in HTML?
Javascript read file without using input
These links help you to find answer.
This Can do a trick.
HTML
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
JS
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}

How to read the first line of .txt file?

can anyone one help how to read the first line of .txt file? I have input type file that upload example.txt then I would like to grab the first line from that code. I tried something like this:
<input type="file" id="fileUpload" name="fileUpload"/> MyTest.txt //file name
function confirmFileSubmit(){
var fileName = $('#fileUpload').val();
alert($('#fileUpload').split('\n')[0]);
}
After I run my code this just outputted file name in alert box. I'm not sure how I can read the content of the file. If anyone can help please let me know.
You'll need the FileReader for that
function confirmFileSubmit(){
var input = document.getElementById('fileUpload'); // get the input
var file = input.files[0]; // assuming single file, no multiple
var reader = new FileReader();
reader.onload = function(e) {
var text = reader.result; // the entire file
var firstLine = text.split('\n').shift(); // first line
console.log(firstLine); // use the console for debugging
}
reader.readAsText(file, 'UTF-8'); // or whatever encoding you're using
// UTF-8 is default, so this argument
} // is not really needed

Parsing an existing text file with no user selection

Long story short, I am looking to parse a text file (eventually kept on a server, but for now tested locally) that will update content, but will never change file location, name or extension.
Let's say the file is called feed.txt in C:\files. So, I always want my parser to traverse through the static C:\files\feed.html.
I know am all familiar with
<input type="file" name="file" id="file">
for user selection, but I want my javascipt parser to skip that all together, grab the file, parse it as such:
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file
console.log(this.result);
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
console.log(lines[line]);
}
};
reader.readAsText(file);
};
and have certain strings being displayed back into my html (code not written yet - still on the parsing part). How do I go about skipping user file selection and just having the javascript know which file (and where) to parse?
Thanks!

Categories