Reader onload function not adding split lines to predefined Array - javascript

I am trying to load a file using the input tag in html with type 'file'
<input type="file">
And then with this file, I am trying to split each line and return the resulting array into an array called lines.
I have tried moving the console.log(lines) around but I only get the correct result when the console.log is inside the .onload function.
var input = document.querySelector('input[type="file"]')
input.addEventListener('change', function (e) {
let lines = new Array();
console.log(input.files)
const reader = new FileReader()
reader.onload = function () {
lines = reader.result.split('\n');
}
reader.readAsText(input.files[0]);
console.log(lines)
})
How can i ensure that the lines array has had the correct split lines put into it so that I can then use the lines array in other parts of my overall function

just try push split value in array. it may work for you.
var input = document.querySelector('input[type="file"]')
let lines = [];
input.addEventListener('change', function (e) {
const reader = new FileReader()
reader.onload = function () {
lines.push(reader.result.split('\n'));
}
reader.readAsText(input.files[0]);
console.log(lines);
})
<input type="file">

Related

is there a way to take text from input type file and proccess the text in javascript

i am trying to preview a text from a text file through input type file using javascript
i tried using the file directly in my code but error is prompted saying file is undefiend
but when i use file.value or print file to console an object from file is displayed
function readInsideFile()
{
const [file] = document.querySelector('input[type=file]').files;
console.log(file);
const reader = new FileReader();
// this will then display a text file
var text = reader.readAsText(file);
console.log(text);
var firstLine = text.split('\n').shift(); // first line
var sensorsoutputfield = document.getElementById("Rectangle_8_bu");
sensorsoutputfield.innerHTML = firstLine;
}
Yes, you can read files, but you must write lambda functions for reader. Use this
Example
function readInsideFile()
{
const files = document.querySelector('input[type=file]').files;
console.log(files);
const reader = new FileReader();
// this will then display a text file
reader.onload = () => {
var content = reader.result;
console.log(text);
var firstLine = text.split('\n').shift(); // first line
var sensorsoutputfield =
document.getElementById("Rectangle_8_bu");
sensorsoutputfield.innerHTML = firstLine;
}
reader.readAsText(this.files[0]);
}

Reading a file from html input tag to a variable

I am trying to be able to read the contents of a file that is uploaded via the input tag to a variable where I can then use an algorithm that takes the contents of a .txt file and decrypts it:
<input type="button" value="decrypt" id="decryptbutton">
function decrypt() {
const selectedFile = document.getElementById('input').files[0];
var fr = new FileReader();
let ciphertext = fr.readAsText(selectedFile);
decrypt(ciphertext, key);
}
however, this does not seem to work. I have searched the internet already to try and find the answer, but I still can't figure out how to put the contents of the uploaded file into a variable.
Is this what you're looking for?
The reason you're having issues is that the returned value is a promise which isn't present yet until the promise resolves. The way to get around it is to set the value in a function that you call on success of the promise .then( res => { theFunctionToSetValue(res) }); Then you set the variable/innerHTML with the function that's called on success.
With the code I provided, you would call decipher inside of setOutput()
document.addEventListener("DOMContentLoaded", function() {
const uploadBtn = document.getElementById("upload");
const output = document.getElementById("output");
var outputText;
function setOutput(response) {
outputText = response;
output.innerHTML = outputText;
};
uploadBtn.addEventListener("change", function() {
var fr = new FileReader();
fr.onload = function() {
uploadBtn.textContent = fr.result;
}
outputText = uploadBtn.files[0].text().then( res => { setOutput(res) });
});
});
<input type="file" id="upload">
<div id="output"></div>

How to grab everything but the first line from .txt with JavaScript FileReader?

I have text file and I would like to grab everything but my first line. Also I would like to check how many columns have each of my rows. How that can be done with JavaScript File Reader? I have used code bleow for reading just the first row:
var fileExist = $('#fileUpload')[0];
var reader = new FileReader();
var file = fileExist.files[0];
reader.onload = function(e) {
var text = reader.result;
var firstLine = text.split('\n').shift();
var columnNames = firstLine.split('\t');
console.log(columnNames);
}
reader.readAsText(file, 'UTF-8');
Just get rid of the first line with pop() and then iterate through the Array.
var fileExist = $('#fileUpload')[0];
var reader = new FileReader();
var file = fileExist.files[0];
reader.onload = function (e) {
var text = reader.result;
var allLines = text.split('\n');
// Print the colomn names
console.log(allLines.pop().split('\t'));
// Get rid of first line
allLines.pop();
// Print all the other lines
allLines.forEach(function (line) {
console.log(line.split('\t'));
});
}
reader.readAsText(file, 'UTF-8');

Javascript split blob as strings

Say you parse a text file with fileReader:
function show() {
var file = document.getElementById('myFile');
var data = file.files[0];
var fileRead = new FileReader();
fileRead.onload = function() { document.getElementById('out').appendChild(document.createTextNode(' ' + fileRead.result)) }
fileRead.readAsText(data);
}
How do you split a blob object (raw data) with the split function which works only on strings?
If I convert the blob to string and then call readAsText it reasonably complains that the data variable (containing text) is not a blob object.
So, basically I want to use the split function on the blob text object.
You can just do it in the onload callback.
var file = document.getElementById('myfile');
var data = file.files[0];
var var fileReader = new FileReader();
fileReader.onload = function() {
let strings = fileReader.result.split(' ');
strings.forEach(function(string) {
//Your code here
})
}
fileReader.readAsText(data)
If you want blob objects representing each split string, you would have to build the blob objects in the foreach loop.

FileReader read file undefined result

I wish to read the contents of an upload file into a Javascript variable.
The program used to work using file.getAsBinary but this is now deprecated and needs to be updated to use FileReader()
A form has a file upload selection an onsubmit runs a function uploadDB() in a javascript.
The variable dbname is passed okay as is the file name from the upload selection
I can see it with an alert or console.log.
The final bfile variable to receive the file text is undefined. I have tried both readAsText and ReadAsBinary but bfile is undefined. The var declaration is in function uploadDB() and should be global to the inner function. If scope is somehow a problem how do I get the result in the bfile variable.
Its probably simple but I cannot get it to work. Can someone suggest something please.
The html section is;
<form onsubmit="uploadDB()"; method="post">
Database <input type=text name="dbName" id="dbName" size=20>
<input type=file id="metaDescFile" size=50 >
<input type=submit value="Submit">
</form>
The js script is similar to (extraneous stuff edited out);
<script language="javascript" type="text/javascript">
<!--
var uploadDB = function() {
var input = document.getElementById('metaDescFile');
var fname = document.getElementById('metaDescFile').value;
var file=input.files[0];
var bfile;
reader = new FileReader();
reader.onload = function(e) { bfile = e.target.result }
reader.readAsText(file);
alert(bfile); // this shows bfile as undefined
// other stuff
}
as bfile gets set in the onload callback you won't be able to access outside that callback because the code is evaluated before the callback is fired.
Try this:
reader = new FileReader();
reader.onload = function(e) {
bfile = e.target.result
alert(bfile); // this shows bfile
}
reader.readAsText(file);
Here is one answer to get the actual final byte array , just using FileReader and ArrayBuffer :
const test_function = async () => {
... ... ...
const get_file_array = (file) => {
return new Promise((acc, err) => {
const reader = new FileReader();
reader.onload = (event) => { acc(event.target.result) };
reader.onerror = (err) => { err(err) };
reader.readAsArrayBuffer(file);
});
}
const temp = await get_file_array(files[0])
console.log('here we finally ve the file as a ArrayBuffer : ',temp);
const fileb = new Uint8Array(fileb)
... ... ...
}
where file is directly the File object u want to read , notice that this is an async function...

Categories

Resources