"change" event lags one step behind javascript - 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;
};
}

Related

HTML JavaScript print from file onto page

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>

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");
}
}
});

How to read a text file saved on my computer using javascript

I have a text file that is being updated regularly and I want to know if it is possible to read the file, line by line, with javascript and save the values in variables and then update the html page with the new values every time the page is loaded. The html page is a simple page to display information at work, not a live web page, and does not require any user input other than just navigating between the two pages. The text file is on a network drive that everyone has access to. Here is an example of what I'm trying to accomplish:
var value1;
var value2;
Read the file with javascript if possible and extract data and assign to value1 and value2.
document.getElementsByClassName("class for <p>")[0].innerHTML = value;
document.getElementsByClassName("class for another <p>")[0].innerHTML = value;
I have googled this but was not able to find anything that worked. If this is not possible with JS, any suggestions on how this can be done differently. Thanks in advance.
At first, you need to use a input[type=file] to get a File.
<input type=file id=file/>
<div id=result></div>
And then use FileReader to read file to target format, just like base64, text, buffer.
const file = document.getElementById('file').files[0]
const result = document.getElementById('result')
const reader = new FileReader
reader.addEventListener('load', () => {
result.innerHTML = reader.result
})
reader.readAsText(file, 'UTF-8')
See: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
You could use the javascript FileReader and input type="file" to read the local files in your machine. Please see the below attached code for example.
<!DOCTYPE html>
<html>
<head>
<script>
function OnFileLoad() {
var file = document.getElementById("FileReader").files[0];
var textType = /text.*/;
var fileDisplayArea = document.getElementById("FileContent");
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>
</head>
<body>
<input type="file" id="FileReader" onchange="OnFileLoad()" />
<div id="FileContent">Your content will appear here</div>
</body>
</html>
In order to specify the file path you might need to have a server as well. I have attached a sample code here with. You can find the details regarding Specifying the file path here and issues that will happen to read file without a server here
<!DOCTYPE html>
<html>
<head>
<script>
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
var fileDisplayArea = document.getElementById("FileContent");
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
fileDisplayArea.innerText = allText;
}
} else {
fileDisplayArea.innerText = "File not supported!"
}
}
rawFile.send(null);
}
readTextFile("file:///C:/Users/t0423/Desktop/test.js")
</script>
</head>
<body>
<div id="FileContent">Your content will appear here</div>
</body>
</html>

Reading a text file using Javascript

The following code should read the content of a text file which is in the current directory upon load, and display it on the html page. I tried modifying by my self. But it does not give an output. Is there an easier way to get this result using another method? or please help figure out what is wrong with this code?
<html>
<head>
<meta http-equiv='Content-type' content='text/html;charset=UTF-8' >
<script>
function startRead()
{
// obtain input element through DOM
var file = document.getElementById("\\file.txt").files[0]
if(file)
{
getAsText(file);
}
}
function getAsText(readFile)
{
var reader;
try
{
reader = new FileReader();
}catch(e)
{
document.getElementById('output').innerHTML =
"Error: seems File API is not supported on your browser";
return;
}
// Read file into memory as UTF-8
reader.readAsText(readFile, "UTF-8");
// Handle progress, success, and errors
reader.onload = loaded;
reader.onerror = errorHandler;
}
function loaded(evt)
{
// Obtain the read file data
var fileString = evt.target.result;
document.getElementById('output').innerHTML = fileString;
}
function errorHandler(evt)
{
if(evt.target.error.code == evt.target.error.NOT_READABLE_ERR)
{
// The file could not be read
document.getElementById('output').innerHTML = "Error reading file..."
}
}
//Start reading file on load
window.addEventListener("load", startRead() { }, false);
</script>
</head>
<body>
<pre>
<code id="output">
</code>
</pre>
</body>
</html>
Given below is the code which I modified to get the above code. My intention was. As I open the html file it would read the text file which is in the current directory and display the content.
<html>
<head>
<meta http-equiv='Content-type' content='text/html;charset=UTF-8' >
<script>
function startRead()
{
// obtain input element through DOM
var file = document.getElementById("file").files[0];
if(file)
{
getAsText(file);
}
}
function getAsText(readFile)
{
var reader;
try
{
reader = new FileReader();
}catch(e)
{
document.getElementById('output').innerHTML =
"Error: seems File API is not supported on your browser";
return;
}
// Read file into memory as UTF-8
reader.readAsText(readFile, "UTF-8");
// Handle progress, success, and errors
reader.onload = loaded;
reader.onerror = errorHandler;
}
function loaded(evt)
{
// Obtain the read file data
var fileString = evt.target.result;
document.getElementById('output').innerHTML = fileString;
}
function errorHandler(evt)
{
if(evt.target.error.code == evt.target.error.NOT_READABLE_ERR)
{
// The file could not be read
document.getElementById('output').innerHTML = "Error reading file..."
}
}
</script>
</head>
<body>
<input id="file" type="file" multiple onchange="startRead()">
<pre>
<code id="output">
</code>
</pre>
</body>
</html>
Try this snippet, I just tried and it works :)!
Live Demo (With Input File)
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) {
var content = reader.result;
//Here the content has been read successfuly
alert(content);
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
<input type="file" id="fileInput">
Without Input File
Function
function readTextFile(file){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
And to test it
Test
Notice: I tried it, but it works only in firefox
<html>
<head></head>
<body>
<input type="file" id="openfile" />
<br>
<pre id="filecontents"></pre>
<script type="text/javascript">
document.getElementById("openfile").addEventListener('change', function() {
var fr = new FileReader();
fr.onload = function() {
document.getElementById("filecontents").textContent = this.result;
}
fr.readAsText(this.files[0]);
})
</script>
</body>
</html>
this code works
<script type="text/javascript">
document.getElementById("openfile").addEventListener('change', function(){
var fr= new FileReader();
fr.onload= function(){
document.getElementById("readfile").textContent=this.result;
}
fr.readAsText(this.files[0]);
})
</script>
<html>
<head>
<title>reading file</title>
</head>
<body>
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">
<hr>
<textarea style="width:500px;height: 400px" id="output"></textarea>
<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>

Why is chrome showing error " The object store currently does not support blob values" when trying to store file in IndexedDB?

I am new to Javascript and IndexedDB. Currently I am writing code for a simple utility which uploads file(s) and stores them in IndexedDB. Then user has the option of either seeing the file names or the contents of the file, which is directly read from stored files in IndexedDB.
Following is my javascript code-
var db;
var display="";
function indexedDOok(){
return "indexedDB" in window;
}
document.addEventListener("DOMContentLoaded", function(){
if(!indexedDOok())
return;
var openRequest = indexedDB.open("fileIndex", 1);
openRequest.onupgradeneeded = function(e){
var thisDB = e.target.result;
if(!thisDB.objectStoreNames.contains("docs")){
thisDB.createObjectStore("docs", {autoIncrement:true});
console.log("Database upgrading....");
}
};
openRequest.onsuccess = function(e){
db = e.target.result;
console.log("Database created");
document.querySelector("#fileSelector").addEventListener("change", handleFileSelection, false);
document.querySelector("#displayButton").addEventListener("click", displayContent, false);
document.querySelector("#getButton").addEventListener("click", getFiles, false);
};
openRequest.onerror = function(e){
console.log(e.target.result);
};
}, false);
function handleFileSelection(e){
console.log("Inside file selection handler...");
var files = e.target.files;
if(!files){
console.log("Files selection failed. Select again");
return;
}//if
try{
var transaction = db.transaction(["docs"],"readwrite");
}catch(ex){
console.log("Exception in opening transaction, "+ex.message);
return;
}//catch
transaction.onerror = function(evt){
console.log("transaction.onerror() fired in handleFileSelection(), error code: "+ (evt.target.error? evt.target.error: evt.target.errorCode));
};
transaction.onabort = function(){
console.log("transaction.onabort() fired in handFileSelection()");
};
transaction.oncomplete = function(){
console.log("transaction.oncomplete() fired in handFileSelection()");
};
try{
var store = transaction.objectStore("docs");
for(var i=0; i<files.length; i++){
file = files[i];
var request = store.put(file);
request.onsuccess = function(){
console.log(files.length);
console.log(file.name+" has been successfully added in table");
};
request.onerror = function(evt){
console.log("Error..."+file.name+" file not added", evt.target.error.name);
};
}
} catch(ex){
console.log("Transaction and/or put() exception in adding file to database...."+ ex.message);
return;
}
};
function getFiles(){
var transaction = db.transaction(["docs"],"readonly");
var cursor = transaction.objectStore("docs").openCursor();
var s ="";
cursor.onsuccess = function(e){
var res = e.target.result;
console.log("Cursor created");
if(res){
s+= "<p>"+res.value.name+"</p>";
res.continue();
}
document.querySelector("#content").innerHTML = s;
};
};
function displayContent(){
var transaction = db.transaction(["docs"],"readonly");
var cursor = transaction.objectStore("docs").openCursor();
document.querySelector("#content").innerHTML = "";
cursor.onsuccess = function(e){
console.log("Inside displayContent() cursor success...");
var res = e.target.result;
if(res){
console.log(res.value.name+ " is loaded");
readerFile(res.value);
res.continue();
}
};
display="";
};
function readerFile(e){
var reader = new FileReader();
reader.readAsText(e);
reader.onload = function(ex){
var rawData = reader.result;
display = document.querySelector("#content");
display.innerHTML = display.innerHTML + "<h2> "+e.name+ "</h2>";
display.innerHTML = display.innerHTML + rawData;
};
}
Following is my index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="files/dbFile.js"></script>
</head>
<body>
<input type="file" id="fileSelector" multiple>
<br><br>
<button id="displayButton">Display Content</button>
<button id="getButton">Display Files</button>
<pre id="content"></pre>
</body>
</html>
It is running successfully in all the browsers. Files are getting uploaded and stored and also getting read and displayed. But only in Chrome it's giving the error "Failed to execute 'put' on 'IDBObjectStore': The object store currently does not support blob values."
Following is the output of Chrome's console, when I try uploading a file-
Database upgrading....
Database created
Inside file selection handler... dbFile.js:38
Transaction and/or put() exception in adding file to database....Failed to execute 'put' on 'IDBObjectStore': The object store currently does not support blob values. dbFile.js:75
transaction.oncomplete() fired in handFileSelection()
Can someone please help me. Why is this happening? I did a lot of research but found nothing helpful

Categories