How to read same file multiple time in javascript - javascript

I have a requirement where I have to read the file and plot the data using javascript. My file will be updated often so i need to read it every time before plotting.
I have written code to do it once i.e., reading the file and store the data js variables.
index.html
<input type="file" id="csvFileInput" onchange="importData(this.files)"accept=".csv">
fileRead.js
<html>
<head>
<meta charset="utf-8" />
<body>
<input type="file" id="csvFileInput" accept=".csv" onchange="importData(this.files)"><br>
<input type="submit" id="Pfit" value="fit">
<script>
var F_load = [];
var v = [];
var csvpoints = [];
function importData(files){
k = files
handleFiles(files);
// plotGraph("div1",F_load, v);
Pfit.disabled = false;
}
function handleFiles(files) {
// Check for the various File API support.
if (window.FileReader) {
// FileReader are supported.
getAsText(files[0]);
} else {
alert('FileReader are not supported in this browser.');
}
}
function getAsText(fileToRead) {
var reader = new FileReader();
// Read file into memory as UTF-8
reader.readAsText(fileToRead);
// Handle errors load
reader.onload = loadHandler;
reader.onerror = errorHandler;
}
function loadHandler(event) {
var csv = event.target.result;
processData(csv);
}
function processData(csv) {
var allTextLines = csv.split(/\r\n|\n/);
var lines = [];
for (var i=1; i<allTextLines.length; i++) {
data = allTextLines[i].split(';');
csvpoints.push(data);
F_load.push(data[0]);
v.push(data[1]);
}
console.log(F_load);
}
function errorHandler(evt) {
if(evt.target.error.name == "NotReadableError") {
alert("Canno't read file !");
}
}
const fitButton=document.getElementById('Pfit');
fitButton.addEventListener('click',event => {
var k = document.getElementById("csvFileInput").file
importData(k)
});
</script>
</body>
</html>
However, it works for the first time. but when i tried to access for the second time it errored out at getAsText(files[0]); . Could anyone help me on this.

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"];

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

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

HTML5 File Handeling in JavaScript?

What techniques are used to load a file (ASCII or Binary) into a variable (var file = "text";) in JavaScript?
You want to use the new HTML5 File API and XMLHttpRequest 2.
You can listen to files being either selected via a file input or drag & dropped to the browser. Let's talk about the input[type="file"] way.
<input type="file">
Let's listen for files being selected.
var input; // let input be our file input
input.onchange = function (e) {
var files = input.files || [];
var file = files[0];
if (file) {
uploadFile(file);
}
};
What you need to create a real multipart file upload request is a FormData object. This object is a representation of the body of your HTTP POST request.
var uploadFile = function (file) {
var data = new FormData();
data.append('filename', file);
// create a HTTP POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', './script.php', true);
xhr.send(data);
xhr.onloadend = function () {
// code to be executed when the upload finishes
};
};
You can also monitor the upload progress.
xhr.upload.onprogress = function (e) {
var percentage = 100 * e.loaded / e.total;
};
Ask if you need any clarification.
If you want to use the new HTML5 way this is how I did it... keep in mind that I made a method called File() and this is not a true HTML5 method its a wrapper to it... this might be changed in the future so beware (maybe rename it).
HTML:
<html>
<body>
<input type="file" id="files" name="file"/>
<button onclick="load()">Load File</button><br /><br />
<div id="content"></div>
<script>
function load() {
var fileObj = document.getElementById("files");
var fp = new File(fileObj);
fp.read(callback);
}
function callback(text) {
var content = document.getElementById("content");
content.innerHTML = text;
}
</script>
</body>
</html>
JavaScript:
function File(name) {
this.name = document.getElementById(name) ? document.getElementById(name).files : name.files ? name.files : name;
}
// Reads the file from the browser
File.prototype.read = function(callback) {
var files = this.name;
if (!files.length) {
alert('Please select a file!?');
return;
}
var file = files[0];
var reader = new FileReader();
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
callback(evt.target.result);
}
};
var data = file.slice(0, file.size);
reader.readAsBinaryString(data);
}
Have the JavaScript being generated inside a PHP or Rails (or whatever you use server-side) and include the file.
<?php
$my_string = file_get_contents('/path/to/file.txt');
?>
<script>
var my_js_file_string = "<?php echo $my_string; ?>";
...
document.write(my_js_file_string);
</script>

Categories