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
Related
I am trying to read the file using javascript new fileReader() function to convert the file in to binary format but is not supporting in Wix
please support us to resolve this issue to overcome it
var fr=new FileReader();
Hope This helps you :-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<input type="file" />
<!-- writing JavaScript inside html -->
<body>
<input type="file" />
<!-- writing JavaScript inside html -->
<script>
const filename = document.querySelector('input[type="file"]');
filename.addEventListener('change', function (){
// Creating a FileReader object using the constructor.
const filereader = new FileReader();
// Reading a file as plain text
filereader.readAsText(filename.files[0]);
// Call this function to print the contents of the file
// once the file has been read.
filereader.onload = function {
console.log(filereader.result);
};
// Print the error incase there is one
filereader.onerror = function {
console.log("Error: ", filereader.error);
};
},false);
</script>
</body>
</body>
</html>
I think i have found a solution for you :-
try this
/* global FileReader */
$w.onReady(function () {
const fileReader = new FileReader();
fetch('https://static.wixstatic.com/media/e3b156_8646d72618e3420db36dba9156d0b8e7~mv2.jpg/v1/fit/w_512,h_586/o_0.jpeg')
.then(response => response.blob())
.then(blob => fileReader.readAsArrayBuffer(blob));
fileReader.onload = function () {
// your buffer array here. But why you need it? )))
console.log(fileReader.result);
}
})
Replace URL according to your needs.
Refer this Wix Corvid Api Overview
FileReader onload not getting fired on second time when the same file still selected with IE11 but the contents of file has changed, it's getting fired all the time for FireFox,Chrome.
Operation Details
On First Click, its all okay for all browsers(but IE sometime still missing some words from file).
After that I changed the contents of the file.
And then I click second attempt to btnDownload, Firefox and Chrome still reading the updated contents. BUT IE DOES NOT WORK!
.html
<input type="file" id="fileSelect" style="" accept=".csv">
<a type="button" class="btn" id="btnDownload" onclick="csvDownload()"
download> CSV DOWNLOAD </a>
myjavascript.js
var fileInput = document.getElementById("fileSelect"); //<input type="file" id="fileSelect">
var result = "";
readFile = function() {
changeAPInfoName();
if (!isFileSupported()) {
console.log('The browser does not support the API.');
} else {
if (fileInput.files.length > 0) {
var reader = new FileReader();
reader.onload = function() {
result = reader.result;
alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)");
document.getElementById('MY_HIDDEN_FIELD').setAttribute('value',result);
}
reader.readAsText(fileInput.files[0]);
reader.onerror = function() {
console.log('The file cannot be read.'+fileInput.files[0].fileName);
};
}
// EVENT FOR DOWNLOAD BUTTON!!!!
function csvDownload(){
readFile();
// using ajax to sent info from files and get download file.
}
Please help me with following issue.
How can I get to the line in reader.onload method although file contents are changed. alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)"); .
Replace this
reader.onload = function() {
result = reader.result;
alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)");
document.getElementById('MY_HIDDEN_FIELD').setAttribute('value',result);
}
with
reader.addEventListener("load",function(){
result = reader.result;
alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)");
document.getElementById('MY_HIDDEN_FIELD').setAttribute('value',result);
});
I hope this is helpful. I was facing the same problem and I used this method and it worked
Example of working FileReader:
<html>
<head>
<script>
function read(){
//Select the element containing file
var file =document.querySelector('input[type=file]').files[0];
//create a FileReader
reader = new FileReader();
//add a listener
reader.addEventListener('load',function(){
alert(reader.result);
},false);
if(file){
//ReadFile
reader.readAsDataURL(file);//You can read it in many other forms
}
}
</script>
</head>
<body>
<input type="file" name="myFile" id="myFile" onchange="read()">
</body>
</html>
For more on FileReader check this document out : Link
I'm tying to read and output a text file. The Chrome console complains:
caught TypeError: Cannot read property '0' of undefined FinanceDashBoard.html:22"
Not sure what I am doing wrong ?
The code is as follows:
<html>
<head>
<title>Read File (via User Input selection)</title>
</head>
<body>
<main>
<label>Load a text database file: <input type="file" id="txtfile" ></label>
</main>
<script type="text/javascript">
var dbFileElm = document.getElementById('txtfile');
dbFileElm.onchange = function() {
var filePath = dbFileElm.files[0];
var reader = new FileReader();
var output = ""; //placeholder for text output
reader.onload = function (e) {
output = e.target.result;
displayContents(output);
}
reader.readAsText(filePath.files[0]);
}
// Ignore code below it doesn't work yet.
function displayContents(txt) {
var el = document.getElementById('main');
el.innerHTML = txt; //display output in DOM
}
</script>
</body>
</html>
Two mistakes.
1) Change this line:
reader.readAsText(filePath.files[0]);
to this:
reader.readAsText(filePath);
Because filePath is already: dbFileElm.files[0];
2) The main tag has no ID, so getting element by ID main will not work.
Just edit it to:
<main id="main">
You have no elements that have id="main"
Try something like...
<main id="main"> ...
Or if you're trying to populate your text box...
var el = document.getElementById('txtfile');
this post has answer to question
HTML input file selection event not firing upon selecting the same file
and if you set your input value to null, is working for me
dbFileElm.onChange = function() {
this.value = null;
var filePath = dbFileElm.files[0];
var reader = new FileReader();
var output = ""; //placeholder for text output
reader.onload = function (e) {
output = e.target.result;
displayContents(output);
}
reader.readAsText(filePath.files[0]);
}
I want to upload a csv file and process the data inside that file. What is the best method to do so? I prefer not to use php script. I did the following steps. But this method only returns the file name instead of file path.So i didnt get the desired output.
<form id='importPfForm'>
<input type='file' name='datafile' size='20'>
<input type='button' value='IMPORT' onclick='importPortfolioFunction()'/>
</form>
function importPortfolioFunction( arg ) {
var f = document.getElementById( 'importPfForm' );
var fileName= f.datafile.value;
}
So how can i get the data inside that file?
The example below is based on the html5rocks solution. It uses the browser's FileReader() function. Newer browsers only.
See http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files
In this example, the user selects an HTML file. It is displayed in the <textarea>.
<form enctype="multipart/form-data">
<input id="upload" type=file accept="text/html" name="files[]" size=30>
</form>
<textarea class="form-control" rows=35 cols=120 id="ms_word_filtered_html"></textarea>
<script>
function handleFileSelect(evt) {
let files = evt.target.files; // FileList object
// use the 1st file from the list
let f = files[0];
let reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
jQuery( '#ms_word_filtered_html' ).val( e.target.result );
};
})(f);
// Read in the image file as a data URL.
reader.readAsText(f);
}
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
</script>
you can use the new HTML 5 file api to read file contents
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
but this won't work on every browser so you probably need a server side fallback.
The example below shows the basic usage of the FileReader to read the contents of an uploaded file. Here is a working Plunker of this example.
function init() {
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event) {
const reader = new FileReader()
reader.onload = handleFileLoad;
reader.readAsText(event.target.files[0])
}
function handleFileLoad(event) {
console.log(event);
document.getElementById('fileContent').textContent = event.target.result;
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body onload="init()">
<input id="fileInput" type="file" name="file" />
<pre id="fileContent"></pre>
</body>
</html>
There exist some new tools on the blob itself that you can use to read the files content as a promise that makes you not have to use the legacy FileReader
// What you need to listen for on the file input
function fileInputChange (evt) {
for (let file of evt.target.files) {
read(file)
}
}
async function read(file) {
// Read the file as text
console.log(await file.text())
// Read the file as ArrayBuffer to handle binary data
console.log(new Uint8Array(await file.arrayBuffer()))
// Abuse response to read json data
console.log(await new Response(file).json())
// Read large data chunk by chunk
console.log(file.stream())
}
read(new File(['{"data": "abc"}'], 'sample.json'))
Try This
document.getElementById('myfile').addEventListener('change', function() {
var GetFile = new FileReader();
GetFile .onload=function(){
// DO Somthing
document.getElementById('output').value= GetFile.result;
}
GetFile.readAsText(this.files[0]);
})
<input type="file" id="myfile">
<textarea id="output" rows="4" cols="50"></textarea>
FileReaderJS can read the files for you. You get the file content inside onLoad(e) event handler as e.target.result.
The fileReader function read my txt file from the sdcard and the result will be set in the evt.target.result.
I want to write (document.write) this evt.target.result to my html page. What is the best way to show this result on the screen. My filereader function:
function fileReader()
{
var reader = new FileReader();
reader.onload = win;
reader.onerror= fail;
reader.readAsText("/sdcard/mytest.txt");
function win(evt)
{
console.log(evt.target.result);
}
function fail(evt) {
console.log(evt.target.error.code);
}
};
You would need to have a div or something similar on your HTML page to display the result. There's tons of ways to present and style this, but the simplest would be to include the div in your HTML and reference it by id in your JS
<!DOCTYPE html>
<html>
<body>
<!-- Your results will display below -->
<div id="results"></div>
</body>
</html>
and in your JS do this
document.getElementById("results").innerHTML = evt.target.result;