JavaScript - Load a file twice in a row - javascript

Good day,
I have the following code to load a ".TXT" file into a web page
function load(event) {
let fr = new FileReader();
fr.onload = function() {
let load0 = JSON.parse(fr.result);
console.log(load0);
console.log("Ready!");
};
fr.readAsText(event.target.files[0]);
}
function loadInput(event) {
document.getElementById("loadInputButton").click();
}
<html>
<body>
<input type="button" onclick="loadInput(event)" />
<input id="loadInputButton" type="file" accept="text" onchange="load(event)" />
</body>
</html>
It works fine but only once. After I once load the file it will not work anymore. I try to load the same file again but the function produces nothing.
May I ask for your help solving it?
Thank you,
Eugene

Clear the value of the input after using it, so that the change event will fire when you select the same file.
function load(event) {
let fr = new FileReader();
fr.onload = function() {
let load0 = JSON.parse(fr.result);
console.log(load0);
console.log("Ready!");
event.target.value = '';
};
fr.readAsText(event.target.files[0])
}
function loadInput(event) {
document.getElementById("loadInputButton").click();
}
<html>
<body>
<input type="button" onclick="loadInput(event)" />
<input id="loadInputButton" type="file" accept="text" onchange="load(event)" />
</body>
</html>

Related

JavaScript - Reading file with HTML5 FileReader

I'm currently learning JavaScript and I'm struggling to read a txt file and use its contents in the program, what I have so far:
fileBtn.addEventListener("change", function()
{
var content = [];
var file = fileBtn.files[0];
readFile(file, function(data)
{
console.log(JSON.parse(data));
//content.push(JSON.parse(data)) doesn't work, data is undef.
});
});
and a function readFile
function readFile(file, f)
{
var reader = new FileReader();
reader.onload = function(evt)
{
f(evt.target.result);
};
reader.readAsText(file);
}
My txt file is currenty only containing a "1", and it logs this number to the console but I can't work with it, if I try to push it into an array the values is suddenly undefined. My goal is to use the content of the file in the program later on
1 . no need to use JSON.parse if the text file only contain string .
data is containing all the text file content
2 . you need to put var content = [];
globally and not inside the function readFile
follow this snippet of code i think it will solve your problem
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<label for="file-upload" class="custom-file-upload">
Custom Upload
</label>
<input id="file-upload" type="file" />
<input id="log-content" type="button" value="Click Me"/>
</body>
<script>
var content = [];
function readFile(file, f) {
var reader = new FileReader();
reader.onload = function (evt) {
f(evt.target.result);
};
var text = reader.readAsText(file);
}
var fileBtn = document.getElementById("file-upload");
var logContnt = document.getElementById("log-content");
logContnt.addEventListener("click", function () {
alert(content);
})
fileBtn.addEventListener("change", function () {
var file = fileBtn.files[0];
readFile(file, function (data) {
content.push(data);
});
});
</script>
</html>

FileReader returning undefined for File object in JQuery

Can some one tell me why when all the File attributes are printed properly why FileReader.readAsArrayBuffer() is returning undefined in the following code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
$( "#form" ).submit(function( event ) {
event.preventDefault();
var filevar=document.getElementById("file").files[0];
var reader=new FileReader() ;
console.log(filevar.name);
console.log(filevar.size);
console.log(filevar.type);
var file_contents= reader.readAsArrayBuffer(filevar);
console.log(file_contents);
});
});
</script>
<body>
<form action="" method="POST" id="form">
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname"><br>
Choose File : <input name="myFile" type="file" id="file">
<input type="submit" id="submit">
</form>
</body>
</html>
Reading a file is asynchronous. You have to wait until it's done.
var reader = new FileReader();
reader.onload = function(e){
let value = e.value; // alternatively reader.result
// do stuff with your value
};
reader.readAsArrayBuffer(filevar);
.readAsArrayBuffer does not return anything.
Alternatively, you can set up an async function for that so you don't have to use callbacks:
function readFile(file){
return new Promise((res, rej) => {
// create file reader
let reader = new FileReader();
// register event listeners
reader.addEventListener("loadend", e => res(e.target.result));
reader.addEventListener("error", rej);
// read file
reader.readAsArrayBuffer(file);
});
}
async function main(file){
// read file into typed array
let fileArrayBuffer = new Uint8Array(await readFile(file));
// do things with it
console.log(fileArrayBuffer);
}
// register event listener for input
document.querySelector("input[type=file]").addEventListener("change", e => {
let file = e.target.files[0];
main(file);
});
<input type="file">
FileReader is actually an async function. Some files are larger than others and so you do not want to lock the main thread.
If you want to see the result of the file. You should add a call back to the onload function of the reader.
var reader = new FileReader();
reader.onload = function(completionEvent) {
console.log(completionEvent);
// Set the result to whatever you need it as
}
reader.readAsArrayBuffer(filevar);

Getting file contents via FileReader() JavaScript

I am trying to get file contents with FileReader(), JavaScript.
I find this answer: https://stackoverflow.com/a/21962101/2898694
As #Markasoftware said in comments, I am trying to save result to var.
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var myFile = evt.target.files[0];
var reader = new FileReader();
var result;
reader.readAsText(myFile);
reader.onload=function(){
result = reader.result;
console.log(result); // works
}
console.log(result); // not works
}
If I am trying to see content in onload handler all fine, but out of it I can't see result. Why?
Because onload runs asynchrone. console.log(result); // not works is executed before the onload event has fired.
More on that: How do I return the response from an asynchronous call?
example
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
var sizef = document.getElementById('uploadImage').files[0].size;
document.getElementById("uploadPreview").src = oFREvent.target.result;
document.getElementById("uploadImageValue").value = oFREvent.target.result;
};
};
jQuery(document).ready(function(){
$('#viewSource').click(function ()
{
var imgUrl = $('#uploadImageValue').val();
alert(imgUrl);
});
});
</script>
<div>
<input type="hidden" id="uploadImageValue" name="uploadImageValue" value="" />
<img id="uploadPreview" style="width: 150px; height: 150px;" /><br />
<input id="uploadImage" style="width:120px" type="file" size="10" accept="image/jpeg,image/gif, image/png" name="myPhoto" onchange="PreviewImage();" />
</div>
Source file
</body>
</html>

To display text from a txt file using javascript

How to read text from a txt file with one button to browse the file and other button to display text. Pls help me in getting the code. i have tried many codes but othing worked. some code was like this. Thanks in advance
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
//process text to show only lines with "#":
output=output.split("\n").filter(/./.test, /\#/).join("\n");
document.getElementById('main').innerHTML= output;
};//end onload()
reader.readAsText(that.files[0]);
}//end if html5 filelist support
}
</script>
</head>
<body>
<input type="file" onchange='readText(this)' />
<div id="main"></div>
</body>
</html>
You should properly read an article like this: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Dont think this line is working properly:
output=output.split("\n").filter(/./.test, /\#/).join("\n");
Try changing it to:
output=output.split("\n").filter(function(l) {
//return /^\#/.test(l); // Starting with #
return l.indexOf('#') > -1; // Containing #
}).join("\n");
It would be interesting to see if this would work as well:
output=output.split("\n").filter(/\#/.test.bind(/\#/)).join("\n");
The second arguments passed to the .filter method is the context:
array.filter(callback[, thisObject])
Get the input file, use FileReader() to read it,on file load get text that matches the pattern. Finally display it through "main" div. Should work..
HTML :
<input id="fileInput" type="file"/>
<div id="main"></div>
jQuery :
$(function(){
$("#fileInput").change(function(e){
var myFile = e.target.files[0];
var reader = new FileReader();
reader.onload = function(e){
var output = e.target.result;
output=output.split("\n").filter(/./.test, /\#/).join("\n");
$("#main").text(output);
};
reader.readAsText(myFile)
});
}
)
Demo

Get text file content using javascript

I've tried use javascript to open text file and get his name and his content, so right now I'm stuck at string, because I used input - type file to get directory / path.
Anyway, my question what is wrong in the next code, and how can i get text file content using javascript?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Display Text Files</title>
<script type="text/javascript">
var str = document.getElementById('txt').value;
function display() {
if (str != "") {
var filename = str.split("/").pop();
document.getElementById('filename').innerHTML = filename;
}
}
</script>
</head>
<body>
<form method="get" action="#" >
<input type="file" accept="text/plain" id="txt" />
<input type="submit" value="Display Text File" onclick="display();" />
</form>
</body>
</html>
EDIT: I also wanna disable in input file the all files opition (*) to text files only (.txt).
Thanks!
Modern browsers implementing FileReader can do this. To test your browser check if window.FileReader is defined.
Here is some code I wrote only this morning to do just this. In my case I simply drag a file onto the HTML element which is here referenced as panel.in1 but you can also use <input type="file" /> (see the reference below).
if (window.FileReader) {
function dragEvent (ev) {
ev.stopPropagation ();
ev.preventDefault ();
if (ev.type == 'drop') {
var reader = new FileReader ();
reader.onloadend = function (ev) { panel.in1.value += this.result; };
reader.readAsText (ev.dataTransfer.files[0]);
}
}
panel.in1.addEventListener ('dragenter', dragEvent, false);
panel.in1.addEventListener ('dragover', dragEvent, false);
panel.in1.addEventListener ('drop', dragEvent, false);
}
It is the reader.onloadend function which gets the text of the file which you recover in the event handler as this.result.
I got most of the mechanism on how to do this from MDN : https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

Categories